(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["default~app"],{

/***/ "./packages/grafana-data/src/dataframe/CircularDataFrame.ts":
/*!******************************************************************!*\
  !*** ./packages/grafana-data/src/dataframe/CircularDataFrame.ts ***!
  \******************************************************************/
/*! exports provided: CircularDataFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircularDataFrame", function() { return CircularDataFrame; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _MutableDataFrame__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./MutableDataFrame */ "./packages/grafana-data/src/dataframe/MutableDataFrame.ts");
/* harmony import */ var _vector_CircularVector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../vector/CircularVector */ "./packages/grafana-data/src/vector/CircularVector.ts");



/**
 * This dataframe can have values constantly added, and will never
 * exceed the given capacity
 */
var CircularDataFrame = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CircularDataFrame, _super);
    function CircularDataFrame(options) {
        return _super.call(this, undefined, function (buffer) {
            return new _vector_CircularVector__WEBPACK_IMPORTED_MODULE_2__["CircularVector"](tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { buffer: buffer }));
        }) || this;
    }
    return CircularDataFrame;
}(_MutableDataFrame__WEBPACK_IMPORTED_MODULE_1__["MutableDataFrame"]));



/***/ }),

/***/ "./packages/grafana-data/src/dataframe/DataFrameView.ts":
/*!**************************************************************!*\
  !*** ./packages/grafana-data/src/dataframe/DataFrameView.ts ***!
  \**************************************************************/
/*! exports provided: DataFrameView */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataFrameView", function() { return DataFrameView; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

/**
 * This abstraction will present the contents of a DataFrame as if
 * it were a well typed javascript object Vector.
 *
 * NOTE: The contents of the object returned from `view.get(index)`
 * are optimized for use in a loop.  All calls return the same object
 * but the index has changed.
 *
 * For example, the three objects:
 *   const first = view.get(0);
 *   const second = view.get(1);
 *   const third = view.get(2);
 * will point to the contents at index 2
 *
 * If you need three different objects, consider something like:
 *   const first = { ... view.get(0) };
 *   const second = { ... view.get(1) };
 *   const third = { ... view.get(2) };
 */
var DataFrameView = /** @class */ (function () {
    function DataFrameView(data) {
        var _this = this;
        this.data = data;
        this.index = 0;
        var obj = {};
        var _loop_1 = function (i) {
            var field = data.fields[i];
            var getter = function () {
                return field.values.get(_this.index);
            };
            if (!obj.hasOwnProperty(field.name)) {
                Object.defineProperty(obj, field.name, {
                    enumerable: true,
                    get: getter,
                });
            }
            Object.defineProperty(obj, i, {
                enumerable: false,
                get: getter,
            });
        };
        for (var i = 0; i < data.fields.length; i++) {
            _loop_1(i);
        }
        this.obj = obj;
    }
    Object.defineProperty(DataFrameView.prototype, "dataFrame", {
        get: function () {
            return this.data;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DataFrameView.prototype, "length", {
        get: function () {
            return this.data.length;
        },
        enumerable: true,
        configurable: true
    });
    DataFrameView.prototype.get = function (idx) {
        this.index = idx;
        return this.obj;
    };
    DataFrameView.prototype.toArray = function () {
        var arr = [];
        for (var i = 0; i < this.data.length; i++) {
            arr.push(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.get(i)));
        }
        return arr;
    };
    DataFrameView.prototype.toJSON = function () {
        return this.toArray();
    };
    DataFrameView.prototype.forEachRow = function (iterator) {
        for (var i = 0; i < this.data.length; i++) {
            iterator(this.get(i));
        }
    };
    return DataFrameView;
}());



/***/ }),

/***/ "./packages/grafana-data/src/dataframe/FieldCache.ts":
/*!***********************************************************!*\
  !*** ./packages/grafana-data/src/dataframe/FieldCache.ts ***!
  \***********************************************************/
/*! exports provided: FieldCache */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FieldCache", function() { return FieldCache; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../index */ "./packages/grafana-data/src/index.ts");


var FieldCache = /** @class */ (function () {
    function FieldCache(data) {
        this.fields = [];
        this.fieldByName = {};
        this.fieldByType = {};
        this.fields = data.fields.map(function (field, idx) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field, { index: idx })); });
        for (var i = 0; i < data.fields.length; i++) {
            var field = data.fields[i];
            // Make sure it has a type
            if (field.type === _index__WEBPACK_IMPORTED_MODULE_1__["FieldType"].other) {
                var t = Object(_index__WEBPACK_IMPORTED_MODULE_1__["guessFieldTypeForField"])(field);
                if (t) {
                    field.type = t;
                }
            }
            if (!this.fieldByType[field.type]) {
                this.fieldByType[field.type] = [];
            }
            this.fieldByType[field.type].push(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field, { index: i }));
            if (this.fieldByName[field.name]) {
                console.warn('Duplicate field names in DataFrame: ', field.name);
            }
            else {
                this.fieldByName[field.name] = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field, { index: i });
            }
        }
    }
    FieldCache.prototype.getFields = function (type) {
        if (!type) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](this.fields); // All fields
        }
        var fields = this.fieldByType[type];
        if (fields) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](fields);
        }
        return [];
    };
    FieldCache.prototype.hasFieldOfType = function (type) {
        var types = this.fieldByType[type];
        return types && types.length > 0;
    };
    FieldCache.prototype.getFirstFieldOfType = function (type) {
        var arr = this.fieldByType[type];
        if (arr && arr.length > 0) {
            return arr[0];
        }
        return undefined;
    };
    FieldCache.prototype.hasFieldNamed = function (name) {
        return !!this.fieldByName[name];
    };
    /**
     * Returns the first field with the given name.
     */
    FieldCache.prototype.getFieldByName = function (name) {
        return this.fieldByName[name];
    };
    return FieldCache;
}());



/***/ }),

/***/ "./packages/grafana-data/src/dataframe/MutableDataFrame.ts":
/*!*****************************************************************!*\
  !*** ./packages/grafana-data/src/dataframe/MutableDataFrame.ts ***!
  \*****************************************************************/
/*! exports provided: MISSING_VALUE, MutableDataFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MISSING_VALUE", function() { return MISSING_VALUE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MutableDataFrame", function() { return MutableDataFrame; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/dataFrame */ "./packages/grafana-data/src/types/dataFrame.ts");
/* harmony import */ var _processDataFrame__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./processDataFrame */ "./packages/grafana-data/src/dataframe/processDataFrame.ts");
/* harmony import */ var lodash_isArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/isArray */ "./node_modules/lodash/isArray.js");
/* harmony import */ var lodash_isArray__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_isArray__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash_isString__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash/isString */ "./node_modules/lodash/isString.js");
/* harmony import */ var lodash_isString__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash_isString__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils_fieldParser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/fieldParser */ "./packages/grafana-data/src/utils/fieldParser.ts");
/* harmony import */ var _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../vector/ArrayVector */ "./packages/grafana-data/src/vector/ArrayVector.ts");
/* harmony import */ var _vector_vectorToArray__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../vector/vectorToArray */ "./packages/grafana-data/src/vector/vectorToArray.ts");








var MISSING_VALUE = null;
var MutableDataFrame = /** @class */ (function () {
    function MutableDataFrame(source, creator) {
        var e_1, _a;
        var _this = this;
        this.fields = [];
        this.values = {};
        this.first = new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_6__["ArrayVector"]();
        // This creates the underlying storage buffers
        this.creator = creator
            ? creator
            : function (buffer) {
                return new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_6__["ArrayVector"](buffer);
            };
        // Copy values from
        if (source) {
            var name = source.name, labels = source.labels, refId = source.refId, meta = source.meta, fields = source.fields;
            if (name) {
                this.name = name;
            }
            if (labels) {
                this.labels = labels;
            }
            if (refId) {
                this.refId = refId;
            }
            if (meta) {
                this.meta = meta;
            }
            if (fields) {
                try {
                    for (var fields_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
                        var f = fields_1_1.value;
                        this.addField(f);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (fields_1_1 && !fields_1_1.done && (_a = fields_1.return)) _a.call(fields_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
        }
        // Get Length to show up if you use spread
        Object.defineProperty(this, 'length', {
            enumerable: true,
            get: function () {
                return _this.first.length;
            },
        });
    }
    Object.defineProperty(MutableDataFrame.prototype, "length", {
        // Defined for Vector interface
        get: function () {
            return this.first.length;
        },
        enumerable: true,
        configurable: true
    });
    MutableDataFrame.prototype.addFieldFor = function (value, name) {
        return this.addField({
            name: name || '',
            type: Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["guessFieldTypeFromValue"])(value),
        });
    };
    MutableDataFrame.prototype.addField = function (f, startLength) {
        var buffer = undefined;
        if (f.values) {
            if (lodash_isArray__WEBPACK_IMPORTED_MODULE_3___default()(f.values)) {
                buffer = f.values;
            }
            else {
                buffer = f.values.toArray();
            }
        }
        var type = f.type;
        if (!type && ('time' === f.name || 'Time' === f.name)) {
            type = _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].time;
        }
        else {
            if (!type && buffer && buffer.length) {
                type = Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["guessFieldTypeFromValue"])(buffer[0]);
            }
            if (!type) {
                type = _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].other;
            }
        }
        // Make sure it has a name
        var name = f.name;
        if (!name) {
            if (type === _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].time) {
                name = this.values['Time'] ? "Time " + (this.fields.length + 1) : 'Time';
            }
            else {
                name = "Field " + (this.fields.length + 1);
            }
        }
        var field = {
            name: name,
            type: type,
            config: f.config || {},
            values: this.creator(buffer),
        };
        if (type === _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].other) {
            type = Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["guessFieldTypeForField"])(field);
            if (type) {
                field.type = type;
            }
        }
        this.fields.push(field);
        this.first = this.fields[0].values;
        // The Field Already exists
        if (this.values[name]) {
            console.warn("Duplicate field names found: " + name + ", only the first will be accessible");
        }
        else {
            this.values[name] = field.values;
        }
        // Make sure the field starts with a given length
        if (startLength) {
            while (field.values.length < startLength) {
                field.values.add(MISSING_VALUE);
            }
        }
        else {
            this.validate();
        }
        return field;
    };
    MutableDataFrame.prototype.validate = function () {
        var e_2, _a;
        // Make sure all arrays are the same length
        var length = this.fields.reduce(function (v, f) {
            return Math.max(v, f.values.length);
        }, 0);
        try {
            // Add empty elements until everything mastches
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.fields), _c = _b.next(); !_c.done; _c = _b.next()) {
                var field = _c.value;
                while (field.values.length !== length) {
                    field.values.add(MISSING_VALUE);
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
    };
    MutableDataFrame.prototype.addMissingFieldsFor = function (value) {
        var e_3, _a;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](Object.keys(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var key = _c.value;
                if (!this.values[key]) {
                    this.addField({
                        name: key,
                        type: Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["guessFieldTypeFromValue"])(value[key]),
                    });
                }
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
    };
    /**
     * Reverse all values
     */
    MutableDataFrame.prototype.reverse = function () {
        var e_4, _a;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.fields), _c = _b.next(); !_c.done; _c = _b.next()) {
                var f = _c.value;
                f.values.reverse();
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_4) throw e_4.error; }
        }
    };
    /**
     * This will add each value to the corresponding column
     */
    MutableDataFrame.prototype.appendRow = function (row) {
        // Add any extra columns
        for (var i = this.fields.length; i < row.length; i++) {
            this.addField({
                name: "Field " + (i + 1),
                type: Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["guessFieldTypeFromValue"])(row[i]),
            });
        }
        // The first line may change the field types
        if (this.length < 1) {
            for (var i = 0; i < this.fields.length; i++) {
                var f = this.fields[i];
                if (!f.type || f.type === _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].other) {
                    f.type = Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["guessFieldTypeFromValue"])(row[i]);
                }
            }
        }
        for (var i = 0; i < this.fields.length; i++) {
            var f = this.fields[i];
            var v = row[i];
            if (f.type !== _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].string && lodash_isString__WEBPACK_IMPORTED_MODULE_4___default()(v)) {
                if (!f.parse) {
                    f.parse = Object(_utils_fieldParser__WEBPACK_IMPORTED_MODULE_5__["makeFieldParser"])(v, f);
                }
                v = f.parse(v);
            }
            f.values.add(v);
        }
    };
    /**
     * Add all properties of the value as fields on the frame
     */
    MutableDataFrame.prototype.add = function (value, addMissingFields) {
        var e_5, _a;
        if (addMissingFields) {
            this.addMissingFieldsFor(value);
        }
        // Will add one value for every field
        var obj = value;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.fields), _c = _b.next(); !_c.done; _c = _b.next()) {
                var field = _c.value;
                var val = obj[field.name];
                if (field.type !== _types_dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"].string && lodash_isString__WEBPACK_IMPORTED_MODULE_4___default()(val)) {
                    if (!field.parse) {
                        field.parse = Object(_utils_fieldParser__WEBPACK_IMPORTED_MODULE_5__["makeFieldParser"])(val, field);
                    }
                    val = field.parse(val);
                }
                if (val === undefined) {
                    val = MISSING_VALUE;
                }
                field.values.add(val);
            }
        }
        catch (e_5_1) { e_5 = { error: e_5_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_5) throw e_5.error; }
        }
    };
    MutableDataFrame.prototype.set = function (index, value, addMissingFields) {
        var e_6, _a;
        if (index > this.length) {
            throw new Error('Unable ot set value beyond current length');
        }
        if (addMissingFields) {
            this.addMissingFieldsFor(value);
        }
        var obj = value || {};
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.fields), _c = _b.next(); !_c.done; _c = _b.next()) {
                var field = _c.value;
                field.values.set(index, obj[field.name]);
            }
        }
        catch (e_6_1) { e_6 = { error: e_6_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_6) throw e_6.error; }
        }
    };
    /**
     * Get an object with a property for each field in the DataFrame
     */
    MutableDataFrame.prototype.get = function (idx) {
        var e_7, _a;
        var v = {};
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.fields), _c = _b.next(); !_c.done; _c = _b.next()) {
                var field = _c.value;
                v[field.name] = field.values.get(idx);
            }
        }
        catch (e_7_1) { e_7 = { error: e_7_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_7) throw e_7.error; }
        }
        return v;
    };
    MutableDataFrame.prototype.toArray = function () {
        return Object(_vector_vectorToArray__WEBPACK_IMPORTED_MODULE_7__["vectorToArray"])(this);
    };
    /**
     * The simplified JSON values used in JSON.stringify()
     */
    MutableDataFrame.prototype.toJSON = function () {
        return Object(_processDataFrame__WEBPACK_IMPORTED_MODULE_2__["toDataFrameDTO"])(this);
    };
    return MutableDataFrame;
}());



/***/ }),

/***/ "./packages/grafana-data/src/dataframe/index.ts":
/*!******************************************************!*\
  !*** ./packages/grafana-data/src/dataframe/index.ts ***!
  \******************************************************/
/*! exports provided: DataFrameView, FieldCache, CircularDataFrame, MISSING_VALUE, MutableDataFrame, guessFieldTypeFromValue, guessFieldTypeForField, guessFieldTypes, isTableData, isDataFrame, toDataFrame, toLegacyResponseData, sortDataFrame, reverseDataFrame, getTimeField, getDataFrameRow, toDataFrameDTO */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _DataFrameView__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DataFrameView */ "./packages/grafana-data/src/dataframe/DataFrameView.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataFrameView", function() { return _DataFrameView__WEBPACK_IMPORTED_MODULE_0__["DataFrameView"]; });

/* harmony import */ var _FieldCache__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./FieldCache */ "./packages/grafana-data/src/dataframe/FieldCache.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldCache", function() { return _FieldCache__WEBPACK_IMPORTED_MODULE_1__["FieldCache"]; });

/* harmony import */ var _CircularDataFrame__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CircularDataFrame */ "./packages/grafana-data/src/dataframe/CircularDataFrame.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircularDataFrame", function() { return _CircularDataFrame__WEBPACK_IMPORTED_MODULE_2__["CircularDataFrame"]; });

/* harmony import */ var _MutableDataFrame__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MutableDataFrame */ "./packages/grafana-data/src/dataframe/MutableDataFrame.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MISSING_VALUE", function() { return _MutableDataFrame__WEBPACK_IMPORTED_MODULE_3__["MISSING_VALUE"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MutableDataFrame", function() { return _MutableDataFrame__WEBPACK_IMPORTED_MODULE_3__["MutableDataFrame"]; });

/* harmony import */ var _processDataFrame__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./processDataFrame */ "./packages/grafana-data/src/dataframe/processDataFrame.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypeFromValue", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["guessFieldTypeFromValue"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypeForField", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["guessFieldTypeForField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypes", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["guessFieldTypes"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isTableData", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["isTableData"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isDataFrame", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["isDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDataFrame", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["toDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toLegacyResponseData", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["toLegacyResponseData"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sortDataFrame", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["sortDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reverseDataFrame", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["reverseDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTimeField", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["getTimeField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDataFrameRow", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["getDataFrameRow"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDataFrameDTO", function() { return _processDataFrame__WEBPACK_IMPORTED_MODULE_4__["toDataFrameDTO"]; });








/***/ }),

/***/ "./packages/grafana-data/src/dataframe/processDataFrame.ts":
/*!*****************************************************************!*\
  !*** ./packages/grafana-data/src/dataframe/processDataFrame.ts ***!
  \*****************************************************************/
/*! exports provided: guessFieldTypeFromValue, guessFieldTypeForField, guessFieldTypes, isTableData, isDataFrame, toDataFrame, toLegacyResponseData, sortDataFrame, reverseDataFrame, getTimeField, getDataFrameRow, toDataFrameDTO */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypeFromValue", function() { return guessFieldTypeFromValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypeForField", function() { return guessFieldTypeForField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypes", function() { return guessFieldTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTableData", function() { return isTableData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDataFrame", function() { return isDataFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDataFrame", function() { return toDataFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toLegacyResponseData", function() { return toLegacyResponseData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortDataFrame", function() { return sortDataFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverseDataFrame", function() { return reverseDataFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeField", function() { return getTimeField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataFrameRow", function() { return getDataFrameRow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDataFrameDTO", function() { return toDataFrameDTO; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_isNumber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/isNumber */ "./node_modules/lodash/isNumber.js");
/* harmony import */ var lodash_isNumber__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_isNumber__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_isString__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/isString */ "./node_modules/lodash/isString.js");
/* harmony import */ var lodash_isString__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_isString__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_isBoolean__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/isBoolean */ "./node_modules/lodash/isBoolean.js");
/* harmony import */ var lodash_isBoolean__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_isBoolean__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _types_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../types/index */ "./packages/grafana-data/src/types/index.ts");
/* harmony import */ var _datetime_moment_wrapper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../datetime/moment_wrapper */ "./packages/grafana-data/src/datetime/moment_wrapper.ts");
/* harmony import */ var _utils_deprecationWarning__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/deprecationWarning */ "./packages/grafana-data/src/utils/deprecationWarning.ts");
/* harmony import */ var _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../vector/ArrayVector */ "./packages/grafana-data/src/vector/ArrayVector.ts");
/* harmony import */ var _MutableDataFrame__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./MutableDataFrame */ "./packages/grafana-data/src/dataframe/MutableDataFrame.ts");
/* harmony import */ var _vector_SortedVector__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../vector/SortedVector */ "./packages/grafana-data/src/vector/SortedVector.ts");

// Libraries



// Types






function convertTableToDataFrame(table) {
    var e_1, _a, e_2, _b;
    var fields = table.columns.map(function (c) {
        var text = c.text, disp = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](c, ["text"]);
        return {
            name: text,
            config: (disp || {}),
            values: new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"](),
            type: _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other,
        };
    });
    try {
        for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](table.rows), _d = _c.next(); !_d.done; _d = _c.next()) {
            var row = _d.value;
            for (var i = 0; i < fields.length; i++) {
                fields[i].values.buffer.push(row[i]);
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
        }
        finally { if (e_1) throw e_1.error; }
    }
    try {
        for (var fields_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
            var f = fields_1_1.value;
            var t = guessFieldTypeForField(f);
            if (t) {
                f.type = t;
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (fields_1_1 && !fields_1_1.done && (_b = fields_1.return)) _b.call(fields_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return {
        fields: fields,
        refId: table.refId,
        meta: table.meta,
        name: table.name,
        length: table.rows.length,
    };
}
function convertTimeSeriesToDataFrame(timeSeries) {
    var e_3, _a;
    var fields = [
        {
            name: timeSeries.target || 'Value',
            type: _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].number,
            config: {
                unit: timeSeries.unit,
            },
            values: new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"](),
        },
        {
            name: 'Time',
            type: _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].time,
            config: {
                unit: 'dateTimeAsIso',
            },
            values: new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"](),
        },
    ];
    try {
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](timeSeries.datapoints), _c = _b.next(); !_c.done; _c = _b.next()) {
            var point = _c.value;
            fields[0].values.buffer.push(point[0]);
            fields[1].values.buffer.push(point[1]);
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_3) throw e_3.error; }
    }
    return {
        name: timeSeries.target,
        labels: timeSeries.tags,
        refId: timeSeries.refId,
        meta: timeSeries.meta,
        fields: fields,
        length: timeSeries.datapoints.length,
    };
}
/**
 * This is added temporarily while we convert the LogsModel
 * to DataFrame.  See: https://github.com/grafana/grafana/issues/18528
 */
function convertGraphSeriesToDataFrame(graphSeries) {
    var x = new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"]();
    var y = new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"]();
    for (var i = 0; i < graphSeries.data.length; i++) {
        var row = graphSeries.data[i];
        x.buffer.push(row[1]);
        y.buffer.push(row[0]);
    }
    return {
        name: graphSeries.label,
        fields: [
            {
                name: graphSeries.label || 'Value',
                type: _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].number,
                config: {},
                values: x,
            },
            {
                name: 'Time',
                type: _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].time,
                config: {
                    unit: 'dateTimeAsIso',
                },
                values: y,
            },
        ],
        length: x.buffer.length,
    };
}
function convertJSONDocumentDataToDataFrame(timeSeries) {
    var e_4, _a;
    var fields = [
        {
            name: timeSeries.target,
            type: _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other,
            config: {
                unit: timeSeries.unit,
                filterable: timeSeries.filterable,
            },
            values: new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"](),
        },
    ];
    try {
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](timeSeries.datapoints), _c = _b.next(); !_c.done; _c = _b.next()) {
            var point = _c.value;
            fields[0].values.buffer.push(point);
        }
    }
    catch (e_4_1) { e_4 = { error: e_4_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_4) throw e_4.error; }
    }
    return {
        name: timeSeries.target,
        labels: timeSeries.tags,
        refId: timeSeries.target,
        meta: { json: true },
        fields: fields,
        length: timeSeries.datapoints.length,
    };
}
// PapaParse Dynamic Typing regex:
// https://github.com/mholt/PapaParse/blob/master/papaparse.js#L998
var NUMBER = /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i;
/**
 * Given a value this will guess the best column type
 *
 * TODO: better Date/Time support!  Look for standard date strings?
 */
function guessFieldTypeFromValue(v) {
    if (lodash_isNumber__WEBPACK_IMPORTED_MODULE_1___default()(v)) {
        return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].number;
    }
    if (lodash_isString__WEBPACK_IMPORTED_MODULE_2___default()(v)) {
        if (NUMBER.test(v)) {
            return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].number;
        }
        if (v === 'true' || v === 'TRUE' || v === 'True' || v === 'false' || v === 'FALSE' || v === 'False') {
            return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].boolean;
        }
        return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].string;
    }
    if (lodash_isBoolean__WEBPACK_IMPORTED_MODULE_3___default()(v)) {
        return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].boolean;
    }
    if (v instanceof Date || Object(_datetime_moment_wrapper__WEBPACK_IMPORTED_MODULE_5__["isDateTime"])(v)) {
        return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].time;
    }
    return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other;
}
/**
 * Looks at the data to guess the column type.  This ignores any existing setting
 */
function guessFieldTypeForField(field) {
    // 1. Use the column name to guess
    if (field.name) {
        var name = field.name.toLowerCase();
        if (name === 'date' || name === 'time') {
            return _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].time;
        }
    }
    // 2. Check the first non-null value
    for (var i = 0; i < field.values.length; i++) {
        var v = field.values.get(i);
        if (v !== null) {
            return guessFieldTypeFromValue(v);
        }
    }
    // Could not find anything
    return undefined;
}
/**
 * @returns a copy of the series with the best guess for each field type
 * If the series already has field types defined, they will be used
 */
var guessFieldTypes = function (series) {
    for (var i = 0; i < series.fields.length; i++) {
        if (!series.fields[i].type) {
            // Somethign is missing a type return a modified copy
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { fields: series.fields.map(function (field) {
                    if (field.type && field.type !== _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other) {
                        return field;
                    }
                    // Calculate a reasonable schema value
                    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field, { type: guessFieldTypeForField(field) || _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other });
                }) });
        }
    }
    // No changes necessary
    return series;
};
var isTableData = function (data) { return data && data.hasOwnProperty('columns'); };
var isDataFrame = function (data) { return data && data.hasOwnProperty('fields'); };
var toDataFrame = function (data) {
    if (data.hasOwnProperty('fields')) {
        // @deprecated -- remove in 6.5
        if (data.hasOwnProperty('rows')) {
            var v = new _MutableDataFrame__WEBPACK_IMPORTED_MODULE_8__["MutableDataFrame"](data);
            var rows = data.rows;
            for (var i = 0; i < rows.length; i++) {
                v.appendRow(rows[i]);
            }
            Object(_utils_deprecationWarning__WEBPACK_IMPORTED_MODULE_6__["deprecationWarning"])('DataFrame', '.rows', 'columnar format');
            return v;
        }
        // DataFrameDTO does not have length
        if (data.hasOwnProperty('length')) {
            return data;
        }
        // This will convert the array values into Vectors
        return new _MutableDataFrame__WEBPACK_IMPORTED_MODULE_8__["MutableDataFrame"](data);
    }
    // Handle legacy docs/json type
    if (data.hasOwnProperty('type') && data.type === 'docs') {
        return convertJSONDocumentDataToDataFrame(data);
    }
    if (data.hasOwnProperty('datapoints')) {
        return convertTimeSeriesToDataFrame(data);
    }
    if (data.hasOwnProperty('data')) {
        return convertGraphSeriesToDataFrame(data);
    }
    if (data.hasOwnProperty('columns')) {
        return convertTableToDataFrame(data);
    }
    console.warn('Can not convert', data);
    throw new Error('Unsupported data format');
};
var toLegacyResponseData = function (frame) {
    var fields = frame.fields;
    var rowCount = frame.length;
    var rows = [];
    for (var i = 0; i < rowCount; i++) {
        var row = [];
        for (var j = 0; j < fields.length; j++) {
            row.push(fields[j].values.get(i));
        }
        rows.push(row);
    }
    if (fields.length === 2) {
        var type = fields[1].type;
        if (!type) {
            type = guessFieldTypeForField(fields[1]) || _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other;
        }
        if (type === _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].time) {
            return {
                alias: fields[0].name || frame.name,
                target: fields[0].name || frame.name,
                datapoints: rows,
                unit: fields[0].config ? fields[0].config.unit : undefined,
                refId: frame.refId,
                meta: frame.meta,
            };
        }
    }
    if (frame.meta && frame.meta.json) {
        return {
            alias: fields[0].name || frame.name,
            target: fields[0].name || frame.name,
            datapoints: fields[0].values.toArray(),
            filterable: fields[0].config ? fields[0].config.filterable : undefined,
            type: 'docs',
        };
    }
    return {
        columns: fields.map(function (f) {
            var name = f.name, config = f.config;
            if (config) {
                // keep unit etc
                var column = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](config, []);
                column.text = name;
                return column;
            }
            return { text: name };
        }),
        type: 'table',
        refId: frame.refId,
        meta: frame.meta,
        rows: rows,
    };
};
function sortDataFrame(data, sortIndex, reverse) {
    if (reverse === void 0) { reverse = false; }
    var field = data.fields[sortIndex];
    if (!field) {
        return data;
    }
    // Natural order
    var index = [];
    for (var i = 0; i < data.length; i++) {
        index.push(i);
    }
    var values = field.values;
    // Numeric Comparison
    var compare = function (a, b) {
        var vA = values.get(a);
        var vB = values.get(b);
        return vA - vB; // works for numbers!
    };
    // String Comparison
    if (field.type === _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].string) {
        compare = function (a, b) {
            var vA = values.get(a);
            var vB = values.get(b);
            return vA.localeCompare(vB);
        };
    }
    // Run the sort function
    index.sort(compare);
    if (reverse) {
        index.reverse();
    }
    // Return a copy that maps sorted values
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, data, { fields: data.fields.map(function (f) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, f, { values: new _vector_SortedVector__WEBPACK_IMPORTED_MODULE_9__["SortedVector"](f.values, index) });
        }) });
}
/**
 * Returns a copy with all values reversed
 */
function reverseDataFrame(data) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, data, { fields: data.fields.map(function (f) {
            var copy = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](f.values.toArray());
            copy.reverse();
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, f, { values: new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_7__["ArrayVector"](copy) });
        }) });
}
var getTimeField = function (series) {
    for (var i = 0; i < series.fields.length; i++) {
        if (series.fields[i].type === _types_index__WEBPACK_IMPORTED_MODULE_4__["FieldType"].time) {
            return {
                timeField: series.fields[i],
                timeIndex: i,
            };
        }
    }
    return {};
};
/**
 * Wrapper to get an array from each field value
 */
function getDataFrameRow(data, row) {
    var e_5, _a;
    var values = [];
    try {
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data.fields), _c = _b.next(); !_c.done; _c = _b.next()) {
            var field = _c.value;
            values.push(field.values.get(row));
        }
    }
    catch (e_5_1) { e_5 = { error: e_5_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_5) throw e_5.error; }
    }
    return values;
}
/**
 * Returns a copy that does not include functions
 */
function toDataFrameDTO(data) {
    var fields = data.fields.map(function (f) {
        return {
            name: f.name,
            type: f.type,
            config: f.config,
            values: f.values.toArray(),
        };
    });
    return {
        fields: fields,
        refId: data.refId,
        meta: data.meta,
        name: data.name,
        labels: data.labels,
    };
}


/***/ }),

/***/ "./packages/grafana-data/src/datetime/datemath.ts":
/*!********************************************************!*\
  !*** ./packages/grafana-data/src/datetime/datemath.ts ***!
  \********************************************************/
/*! exports provided: isMathString, parse, isValid, parseDateMath */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isMathString", function() { return isMathString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValid", function() { return isValid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseDateMath", function() { return parseDateMath; });
/* harmony import */ var lodash_includes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash/includes */ "./node_modules/lodash/includes.js");
/* harmony import */ var lodash_includes__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash_includes__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash_isDate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/isDate */ "./node_modules/lodash/isDate.js");
/* harmony import */ var lodash_isDate__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_isDate__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./moment_wrapper */ "./packages/grafana-data/src/datetime/moment_wrapper.ts");



var units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
function isMathString(text) {
    if (!text) {
        return false;
    }
    if (typeof text === 'string' && (text.substring(0, 3) === 'now' || text.includes('||'))) {
        return true;
    }
    else {
        return false;
    }
}
/**
 * Parses different types input to a moment instance. There is a specific formatting language that can be used
 * if text arg is string. See unit tests for examples.
 * @param text
 * @param roundUp See parseDateMath function.
 * @param timezone Only string 'utc' is acceptable here, for anything else, local timezone is used.
 */
function parse(text, roundUp, timezone) {
    if (!text) {
        return undefined;
    }
    if (typeof text !== 'string') {
        if (Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["isDateTime"])(text)) {
            return text;
        }
        if (lodash_isDate__WEBPACK_IMPORTED_MODULE_1___default()(text)) {
            return Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(text);
        }
        // We got some non string which is not a moment nor Date. TS should be able to check for that but not always.
        return undefined;
    }
    else {
        var time = void 0;
        var mathString = '';
        var index = void 0;
        var parseString = void 0;
        if (text.substring(0, 3) === 'now') {
            time = Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["dateTimeForTimeZone"])(timezone);
            mathString = text.substring('now'.length);
        }
        else {
            index = text.indexOf('||');
            if (index === -1) {
                parseString = text;
                mathString = ''; // nothing else
            }
            else {
                parseString = text.substring(0, index);
                mathString = text.substring(index + 2);
            }
            // We're going to just require ISO8601 timestamps, k?
            time = Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(parseString, _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["ISO_8601"]);
        }
        if (!mathString.length) {
            return time;
        }
        return parseDateMath(mathString, time, roundUp);
    }
}
/**
 * Checks if text is a valid date which in this context means that it is either a Moment instance or it can be parsed
 * by parse function. See parse function to see what is considered acceptable.
 * @param text
 */
function isValid(text) {
    var date = parse(text);
    if (!date) {
        return false;
    }
    if (Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["isDateTime"])(date)) {
        return date.isValid();
    }
    return false;
}
/**
 * Parses math part of the time string and shifts supplied time according to that math. See unit tests for examples.
 * @param mathString
 * @param time
 * @param roundUp If true it will round the time to endOf time unit, otherwise to startOf time unit.
 */
// TODO: Had to revert Andrejs `time: moment.Moment` to `time: any`
function parseDateMath(mathString, time, roundUp) {
    var strippedMathString = mathString.replace(/\s/g, '');
    var dateTime = time;
    var i = 0;
    var len = strippedMathString.length;
    while (i < len) {
        var c = strippedMathString.charAt(i++);
        var type = void 0;
        var num = void 0;
        var unit = void 0;
        if (c === '/') {
            type = 0;
        }
        else if (c === '+') {
            type = 1;
        }
        else if (c === '-') {
            type = 2;
        }
        else {
            return undefined;
        }
        if (isNaN(parseInt(strippedMathString.charAt(i), 10))) {
            num = 1;
        }
        else if (strippedMathString.length === 2) {
            num = strippedMathString.charAt(i);
        }
        else {
            var numFrom = i;
            while (!isNaN(parseInt(strippedMathString.charAt(i), 10))) {
                i++;
                if (i > 10) {
                    return undefined;
                }
            }
            num = parseInt(strippedMathString.substring(numFrom, i), 10);
        }
        if (type === 0) {
            // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M)
            if (num !== 1) {
                return undefined;
            }
        }
        unit = strippedMathString.charAt(i++);
        if (!lodash_includes__WEBPACK_IMPORTED_MODULE_0___default()(units, unit)) {
            return undefined;
        }
        else {
            if (type === 0) {
                if (roundUp) {
                    dateTime.endOf(unit);
                }
                else {
                    dateTime.startOf(unit);
                }
            }
            else if (type === 1) {
                dateTime.add(num, unit);
            }
            else if (type === 2) {
                dateTime.subtract(num, unit);
            }
        }
    }
    return dateTime;
}


/***/ }),

/***/ "./packages/grafana-data/src/datetime/index.ts":
/*!*****************************************************!*\
  !*** ./packages/grafana-data/src/datetime/index.ts ***!
  \*****************************************************/
/*! exports provided: ISO_8601, setLocale, getLocaleData, isDateTime, toUtc, toDuration, dateTime, dateTimeAsMoment, dateTimeForTimeZone, getTimeZoneGroups, dateMath, rangeUtil */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _datemath__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./datemath */ "./packages/grafana-data/src/datetime/datemath.ts");
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "dateMath", function() { return _datemath__WEBPACK_IMPORTED_MODULE_0__; });
/* harmony import */ var _rangeutil__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rangeutil */ "./packages/grafana-data/src/datetime/rangeutil.ts");
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "rangeUtil", function() { return _rangeutil__WEBPACK_IMPORTED_MODULE_1__; });
/* harmony import */ var _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./moment_wrapper */ "./packages/grafana-data/src/datetime/moment_wrapper.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ISO_8601", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["ISO_8601"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setLocale", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["setLocale"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLocaleData", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["getLocaleData"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isDateTime", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["isDateTime"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toUtc", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["toUtc"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDuration", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["toDuration"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTime", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["dateTime"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTimeAsMoment", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["dateTimeAsMoment"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTimeForTimeZone", function() { return _moment_wrapper__WEBPACK_IMPORTED_MODULE_2__["dateTimeForTimeZone"]; });

/* harmony import */ var _timezones__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timezones */ "./packages/grafana-data/src/datetime/timezones.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTimeZoneGroups", function() { return _timezones__WEBPACK_IMPORTED_MODULE_3__["getTimeZoneGroups"]; });

// Names are too general to export globally







/***/ }),

/***/ "./packages/grafana-data/src/datetime/moment_wrapper.ts":
/*!**************************************************************!*\
  !*** ./packages/grafana-data/src/datetime/moment_wrapper.ts ***!
  \**************************************************************/
/*! exports provided: ISO_8601, setLocale, getLocaleData, isDateTime, toUtc, toDuration, dateTime, dateTimeAsMoment, dateTimeForTimeZone */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ISO_8601", function() { return ISO_8601; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setLocale", function() { return setLocale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocaleData", function() { return getLocaleData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDateTime", function() { return isDateTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toUtc", function() { return toUtc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDuration", function() { return toDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTime", function() { return dateTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTimeAsMoment", function() { return dateTimeAsMoment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTimeForTimeZone", function() { return dateTimeForTimeZone; });
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! moment */ "./node_modules/moment/moment.js");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_0__);
/* tslint:disable:import-blacklist ban ban-types */

var ISO_8601 = moment__WEBPACK_IMPORTED_MODULE_0___default.a.ISO_8601;
var setLocale = function (language) {
    moment__WEBPACK_IMPORTED_MODULE_0___default.a.locale(language);
};
var getLocaleData = function () {
    return moment__WEBPACK_IMPORTED_MODULE_0___default.a.localeData();
};
var isDateTime = function (value) {
    return moment__WEBPACK_IMPORTED_MODULE_0___default.a.isMoment(value);
};
var toUtc = function (input, formatInput) {
    return moment__WEBPACK_IMPORTED_MODULE_0___default.a.utc(input, formatInput);
};
var toDuration = function (input, unit) {
    return moment__WEBPACK_IMPORTED_MODULE_0___default.a.duration(input, unit);
};
var dateTime = function (input, formatInput) {
    return moment__WEBPACK_IMPORTED_MODULE_0___default()(input, formatInput);
};
var dateTimeAsMoment = function (input) {
    return dateTime(input);
};
var dateTimeForTimeZone = function (timezone, input, formatInput) {
    if (timezone === 'utc') {
        return toUtc(input, formatInput);
    }
    return dateTime(input, formatInput);
};


/***/ }),

/***/ "./packages/grafana-data/src/datetime/rangeutil.ts":
/*!*********************************************************!*\
  !*** ./packages/grafana-data/src/datetime/rangeutil.ts ***!
  \*********************************************************/
/*! exports provided: getRelativeTimesList, describeTextRange, describeTimeRange, isValidTimeSpan */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRelativeTimesList", function() { return getRelativeTimesList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "describeTextRange", function() { return describeTextRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "describeTimeRange", function() { return describeTimeRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidTimeSpan", function() { return isValidTimeSpan; });
/* harmony import */ var lodash_each__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash/each */ "./node_modules/lodash/each.js");
/* harmony import */ var lodash_each__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash_each__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash_groupBy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/groupBy */ "./node_modules/lodash/groupBy.js");
/* harmony import */ var lodash_groupBy__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_groupBy__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _datemath__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./datemath */ "./packages/grafana-data/src/datetime/datemath.ts");
/* harmony import */ var _moment_wrapper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./moment_wrapper */ "./packages/grafana-data/src/datetime/moment_wrapper.ts");




var spans = {
    s: { display: 'second' },
    m: { display: 'minute' },
    h: { display: 'hour' },
    d: { display: 'day' },
    w: { display: 'week' },
    M: { display: 'month' },
    y: { display: 'year' },
};
var rangeOptions = [
    { from: 'now/d', to: 'now/d', display: 'Today', section: 2 },
    { from: 'now/d', to: 'now', display: 'Today so far', section: 2 },
    { from: 'now/w', to: 'now/w', display: 'This week', section: 2 },
    { from: 'now/w', to: 'now', display: 'This week so far', section: 2 },
    { from: 'now/M', to: 'now/M', display: 'This month', section: 2 },
    { from: 'now/M', to: 'now', display: 'This month so far', section: 2 },
    { from: 'now/y', to: 'now/y', display: 'This year', section: 2 },
    { from: 'now/y', to: 'now', display: 'This year so far', section: 2 },
    { from: 'now-1d/d', to: 'now-1d/d', display: 'Yesterday', section: 1 },
    {
        from: 'now-2d/d',
        to: 'now-2d/d',
        display: 'Day before yesterday',
        section: 1,
    },
    {
        from: 'now-7d/d',
        to: 'now-7d/d',
        display: 'This day last week',
        section: 1,
    },
    { from: 'now-1w/w', to: 'now-1w/w', display: 'Previous week', section: 1 },
    { from: 'now-1M/M', to: 'now-1M/M', display: 'Previous month', section: 1 },
    { from: 'now-1y/y', to: 'now-1y/y', display: 'Previous year', section: 1 },
    { from: 'now-5m', to: 'now', display: 'Last 5 minutes', section: 3 },
    { from: 'now-15m', to: 'now', display: 'Last 15 minutes', section: 3 },
    { from: 'now-30m', to: 'now', display: 'Last 30 minutes', section: 3 },
    { from: 'now-1h', to: 'now', display: 'Last 1 hour', section: 3 },
    { from: 'now-3h', to: 'now', display: 'Last 3 hours', section: 3 },
    { from: 'now-6h', to: 'now', display: 'Last 6 hours', section: 3 },
    { from: 'now-12h', to: 'now', display: 'Last 12 hours', section: 3 },
    { from: 'now-24h', to: 'now', display: 'Last 24 hours', section: 3 },
    { from: 'now-2d', to: 'now', display: 'Last 2 days', section: 0 },
    { from: 'now-7d', to: 'now', display: 'Last 7 days', section: 0 },
    { from: 'now-30d', to: 'now', display: 'Last 30 days', section: 0 },
    { from: 'now-90d', to: 'now', display: 'Last 90 days', section: 0 },
    { from: 'now-6M', to: 'now', display: 'Last 6 months', section: 0 },
    { from: 'now-1y', to: 'now', display: 'Last 1 year', section: 0 },
    { from: 'now-2y', to: 'now', display: 'Last 2 years', section: 0 },
    { from: 'now-5y', to: 'now', display: 'Last 5 years', section: 0 },
];
var absoluteFormat = 'YYYY-MM-DD HH:mm:ss';
var rangeIndex = {};
lodash_each__WEBPACK_IMPORTED_MODULE_0___default()(rangeOptions, function (frame) {
    rangeIndex[frame.from + ' to ' + frame.to] = frame;
});
function getRelativeTimesList(timepickerSettings, currentDisplay) {
    var groups = lodash_groupBy__WEBPACK_IMPORTED_MODULE_1___default()(rangeOptions, function (option) {
        option.active = option.display === currentDisplay;
        return option.section;
    });
    // _.each(timepickerSettings.time_options, (duration: string) => {
    //   let info = describeTextRange(duration);
    //   if (info.section) {
    //     groups[info.section].push(info);
    //   }
    // });
    return groups;
}
function formatDate(date) {
    return date.format(absoluteFormat);
}
// handles expressions like
// 5m
// 5m to now/d
// now/d to now
// now/d
// if no to <expr> then to now is assumed
function describeTextRange(expr) {
    var isLast = expr.indexOf('+') !== 0;
    if (expr.indexOf('now') === -1) {
        expr = (isLast ? 'now-' : 'now') + expr;
    }
    var opt = rangeIndex[expr + ' to now'];
    if (opt) {
        return opt;
    }
    if (isLast) {
        opt = { from: expr, to: 'now' };
    }
    else {
        opt = { from: 'now', to: expr };
    }
    var parts = /^now([-+])(\d+)(\w)/.exec(expr);
    if (parts) {
        var unit = parts[3];
        var amount = parseInt(parts[2], 10);
        var span = spans[unit];
        if (span) {
            opt.display = isLast ? 'Last ' : 'Next ';
            opt.display += amount + ' ' + span.display;
            opt.section = span.section;
            if (amount > 1) {
                opt.display += 's';
            }
        }
    }
    else {
        opt.display = opt.from + ' to ' + opt.to;
        opt.invalid = true;
    }
    return opt;
}
function describeTimeRange(range) {
    var option = rangeIndex[range.from.toString() + ' to ' + range.to.toString()];
    if (option) {
        return option.display;
    }
    if (Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(range.from) && Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(range.to)) {
        return formatDate(range.from) + ' to ' + formatDate(range.to);
    }
    if (Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(range.from)) {
        var toMoment = _datemath__WEBPACK_IMPORTED_MODULE_2__["parse"](range.to, true);
        return toMoment ? formatDate(range.from) + ' to ' + toMoment.fromNow() : '';
    }
    if (Object(_moment_wrapper__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(range.to)) {
        var from = _datemath__WEBPACK_IMPORTED_MODULE_2__["parse"](range.from, false);
        return from ? from.fromNow() + ' to ' + formatDate(range.to) : '';
    }
    if (range.to.toString() === 'now') {
        var res = describeTextRange(range.from);
        return res.display;
    }
    return range.from.toString() + ' to ' + range.to.toString();
}
var isValidTimeSpan = function (value) {
    if (value.indexOf('$') === 0 || value.indexOf('+$') === 0) {
        return true;
    }
    var info = describeTextRange(value);
    return info.invalid !== true;
};


/***/ }),

/***/ "./packages/grafana-data/src/datetime/timezones.ts":
/*!*********************************************************!*\
  !*** ./packages/grafana-data/src/datetime/timezones.ts ***!
  \*********************************************************/
/*! exports provided: getTimeZoneGroups */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeZoneGroups", function() { return getTimeZoneGroups; });
// List taken from https://stackoverflow.com/questions/38399465/how-to-get-list-of-all-timezones-in-javascript
var getTimeZoneGroups = function () {
    var europeZones = [
        'Europe/Amsterdam',
        'Europe/Andorra',
        'Europe/Astrakhan',
        'Europe/Athens',
        'Europe/Belgrade',
        'Europe/Berlin',
        'Europe/Brussels',
        'Europe/Bucharest',
        'Europe/Budapest',
        'Europe/Chisinau',
        'Europe/Copenhagen',
        'Europe/Dublin',
        'Europe/Gibraltar',
        'Europe/Helsinki',
        'Europe/Istanbul',
        'Europe/Kaliningrad',
        'Europe/Kiev',
        'Europe/Kirov',
        'Europe/Lisbon',
        'Europe/London',
        'Europe/Luxembourg',
        'Europe/Madrid',
        'Europe/Malta',
        'Europe/Minsk',
        'Europe/Monaco',
        'Europe/Moscow',
        'Europe/Oslo',
        'Europe/Paris',
        'Europe/Prague',
        'Europe/Riga',
        'Europe/Rome',
        'Europe/Samara',
        'Europe/Saratov',
        'Europe/Simferopol',
        'Europe/Sofia',
        'Europe/Stockholm',
        'Europe/Tallinn',
        'Europe/Tirane',
        'Europe/Ulyanovsk',
        'Europe/Uzhgorod',
        'Europe/Vienna',
        'Europe/Vilnius',
        'Europe/Volgograd',
        'Europe/Warsaw',
        'Europe/Zaporozhye',
        'Europe/Zurich',
    ];
    var africaZones = [
        'Africa/Abidjan',
        'Africa/Accra',
        'Africa/Algiers',
        'Africa/Bissau',
        'Africa/Cairo',
        'Africa/Casablanca',
        'Africa/Ceuta',
        'Africa/El_Aaiun',
        'Africa/Johannesburg',
        'Africa/Juba',
        'Africa/Khartoum',
        'Africa/Lagos',
        'Africa/Maputo',
        'Africa/Monrovia',
        'Africa/Nairobi',
        'Africa/Ndjamena',
        'Africa/Sao_Tome',
        'Africa/Tripoli',
        'Africa/Tunis',
        'Africa/Windhoek',
    ];
    var asiaZones = [
        'Asia/Almaty',
        'Asia/Amman',
        'Asia/Anadyr',
        'Asia/Aqtau',
        'Asia/Aqtobe',
        'Asia/Ashgabat',
        'Asia/Atyrau',
        'Asia/Baghdad',
        'Asia/Baku',
        'Asia/Bangkok',
        'Asia/Barnaul',
        'Asia/Beirut',
        'Asia/Bishkek',
        'Asia/Brunei',
        'Asia/Chita',
        'Asia/Choibalsan',
        'Asia/Colombo',
        'Asia/Damascus',
        'Asia/Dhaka',
        'Asia/Dili',
        'Asia/Dubai',
        'Asia/Dushanbe',
        'Asia/Famagusta',
        'Asia/Gaza',
        'Asia/Hebron',
        'Asia/Ho_Chi_Minh',
        'Asia/Hong_Kong',
        'Asia/Hovd',
        'Asia/Irkutsk',
        'Asia/Jakarta',
        'Asia/Jayapura',
        'Asia/Jerusalem',
        'Asia/Kabul',
        'Asia/Kamchatka',
        'Asia/Karachi',
        'Asia/Kathmandu',
        'Asia/Khandyga',
        'Asia/Kolkata',
        'Asia/Krasnoyarsk',
        'Asia/Kuala_Lumpur',
        'Asia/Kuching',
        'Asia/Macau',
        'Asia/Magadan',
        'Asia/Makassar',
        'Asia/Manila',
        'Asia/Nicosia',
        'Asia/Novokuznetsk',
        'Asia/Novosibirsk',
        'Asia/Omsk',
        'Asia/Oral',
        'Asia/Pontianak',
        'Asia/Pyongyang',
        'Asia/Qatar',
        'Asia/Qostanay',
        'Asia/Qyzylorda',
        'Asia/Riyadh',
        'Asia/Sakhalin',
        'Asia/Samarkand',
        'Asia/Seoul',
        'Asia/Shanghai',
        'Asia/Singapore',
        'Asia/Srednekolymsk',
        'Asia/Taipei',
        'Asia/Tashkent',
        'Asia/Tbilisi',
        'Asia/Tehran',
        'Asia/Thimphu',
        'Asia/Tokyo',
        'Asia/Tomsk',
        'Asia/Ulaanbaatar',
        'Asia/Urumqi',
        'Asia/Ust-Nera',
        'Asia/Vladivostok',
        'Asia/Yakutsk',
        'Asia/Yangon',
        'Asia/Yekaterinburg',
        'Asia/Yerevan',
    ];
    var antarcticaZones = [
        'Antarctica/Casey',
        'Antarctica/Davis',
        'Antarctica/DumontDUrville',
        'Antarctica/Macquarie',
        'Antarctica/Mawson',
        'Antarctica/Palmer',
        'Antarctica/Rothera',
        'Antarctica/Syowa',
        'Antarctica/Troll',
        'Antarctica/Vostok',
    ];
    var americaZones = [
        'America/Adak',
        'America/Anchorage',
        'America/Araguaina',
        'America/Argentina/Buenos_Aires',
        'America/Argentina/Catamarca',
        'America/Argentina/Cordoba',
        'America/Argentina/Jujuy',
        'America/Argentina/La_Rioja',
        'America/Argentina/Mendoza',
        'America/Argentina/Rio_Gallegos',
        'America/Argentina/Salta',
        'America/Argentina/San_Juan',
        'America/Argentina/San_Luis',
        'America/Argentina/Tucuman',
        'America/Argentina/Ushuaia',
        'America/Asuncion',
        'America/Atikokan',
        'America/Bahia',
        'America/Bahia_Banderas',
        'America/Barbados',
        'America/Belem',
        'America/Belize',
        'America/Blanc-Sablon',
        'America/Boa_Vista',
        'America/Bogota',
        'America/Boise',
        'America/Cambridge_Bay',
        'America/Campo_Grande',
        'America/Cancun',
        'America/Caracas',
        'America/Cayenne',
        'America/Chicago',
        'America/Chihuahua',
        'America/Costa_Rica',
        'America/Creston',
        'America/Cuiaba',
        'America/Curacao',
        'America/Danmarkshavn',
        'America/Dawson',
        'America/Dawson_Creek',
        'America/Denver',
        'America/Detroit',
        'America/Edmonton',
        'America/Eirunepe',
        'America/El_Salvador',
        'America/Fort_Nelson',
        'America/Fortaleza',
        'America/Glace_Bay',
        'America/Godthab',
        'America/Goose_Bay',
        'America/Grand_Turk',
        'America/Guatemala',
        'America/Guayaquil',
        'America/Guyana',
        'America/Halifax',
        'America/Havana',
        'America/Hermosillo',
        'America/Indiana/Indianapolis',
        'America/Indiana/Knox',
        'America/Indiana/Marengo',
        'America/Indiana/Petersburg',
        'America/Indiana/Tell_City',
        'America/Indiana/Vevay',
        'America/Indiana/Vincennes',
        'America/Indiana/Winamac',
        'America/Inuvik',
        'America/Iqaluit',
        'America/Jamaica',
        'America/Juneau',
        'America/Kentucky/Louisville',
        'America/Kentucky/Monticello',
        'America/La_Paz',
        'America/Lima',
        'America/Los_Angeles',
        'America/Maceio',
        'America/Managua',
        'America/Manaus',
        'America/Martinique',
        'America/Matamoros',
        'America/Mazatlan',
        'America/Menominee',
        'America/Merida',
        'America/Metlakatla',
        'America/Mexico_City',
        'America/Miquelon',
        'America/Moncton',
        'America/Monterrey',
        'America/Montevideo',
        'America/Nassau',
        'America/New_York',
        'America/Nipigon',
        'America/Nome',
        'America/Noronha',
        'America/North_Dakota/Beulah',
        'America/North_Dakota/Center',
        'America/North_Dakota/New_Salem',
        'America/Ojinaga',
        'America/Panama',
        'America/Pangnirtung',
        'America/Paramaribo',
        'America/Phoenix',
        'America/Port-au-Prince',
        'America/Port_of_Spain',
        'America/Porto_Velho',
        'America/Puerto_Rico',
        'America/Punta_Arenas',
        'America/Rainy_River',
        'America/Rankin_Inlet',
        'America/Recife',
        'America/Regina',
        'America/Resolute',
        'America/Rio_Branco',
        'America/Santarem',
        'America/Santiago',
        'America/Santo_Domingo',
        'America/Sao_Paulo',
        'America/Scoresbysund',
        'America/Sitka',
        'America/St_Johns',
        'America/Swift_Current',
        'America/Tegucigalpa',
        'America/Thule',
        'America/Thunder_Bay',
        'America/Tijuana',
        'America/Toronto',
        'America/Vancouver',
        'America/Whitehorse',
        'America/Winnipeg',
        'America/Yakutat',
        'America/Yellowknife',
    ];
    var pacificZones = [
        'Pacific/Apia',
        'Pacific/Auckland',
        'Pacific/Bougainville',
        'Pacific/Chatham',
        'Pacific/Chuuk',
        'Pacific/Easter',
        'Pacific/Efate',
        'Pacific/Enderbury',
        'Pacific/Fakaofo',
        'Pacific/Fiji',
        'Pacific/Funafuti',
        'Pacific/Galapagos',
        'Pacific/Gambier',
        'Pacific/Guadalcanal',
        'Pacific/Guam',
        'Pacific/Honolulu',
        'Pacific/Kiritimati',
        'Pacific/Kosrae',
        'Pacific/Kwajalein',
        'Pacific/Majuro',
        'Pacific/Marquesas',
        'Pacific/Nauru',
        'Pacific/Niue',
        'Pacific/Norfolk',
        'Pacific/Noumea',
        'Pacific/Pago_Pago',
        'Pacific/Palau',
        'Pacific/Pitcairn',
        'Pacific/Pohnpei',
        'Pacific/Port_Moresby',
        'Pacific/Rarotonga',
        'Pacific/Tahiti',
        'Pacific/Tarawa',
        'Pacific/Tongatapu',
        'Pacific/Wake',
        'Pacific/Wallis',
    ];
    var australiaZones = [
        'Australia/Adelaide',
        'Australia/Brisbane',
        'Australia/Broken_Hill',
        'Australia/Currie',
        'Australia/Darwin',
        'Australia/Eucla',
        'Australia/Hobart',
        'Australia/Lindeman',
        'Australia/Lord_Howe',
        'Australia/Melbourne',
        'Australia/Perth',
        'Australia/Sydney',
    ];
    var atlanticZones = [
        'Atlantic/Azores',
        'Atlantic/Bermuda',
        'Atlantic/Canary',
        'Atlantic/Cape_Verde',
        'Atlantic/Faroe',
        'Atlantic/Madeira',
        'Atlantic/Reykjavik',
        'Atlantic/South_Georgia',
        'Atlantic/Stanley',
    ];
    var indianZones = [
        'Indian/Chagos',
        'Indian/Christmas',
        'Indian/Cocos',
        'Indian/Kerguelen',
        'Indian/Mahe',
        'Indian/Maldives',
        'Indian/Mauritius',
        'Indian/Reunion',
    ];
    return [
        { label: 'Africa', options: africaZones },
        { label: 'America', options: americaZones },
        { label: 'Antarctica', options: antarcticaZones },
        { label: 'Asia', options: asiaZones },
        { label: 'Atlantic', options: atlanticZones },
        { label: 'Australia', options: australiaZones },
        { label: 'Europe', options: europeZones },
        { label: 'Indian', options: indianZones },
        { label: 'Pacific', options: pacificZones },
    ];
};


/***/ }),

/***/ "./packages/grafana-data/src/index.ts":
/*!********************************************!*\
  !*** ./packages/grafana-data/src/index.ts ***!
  \********************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./packages/grafana-data/src/utils/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registry", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["Registry"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "deprecationWarning", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["deprecationWarning"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSVHeaderStyle", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["CSVHeaderStyle"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "readCSV", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["readCSV"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSVReader", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["CSVReader"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toCSV", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["toCSV"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLogLevel", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["getLogLevel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLogLevelFromKey", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["getLogLevelFromKey"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addLogLevelToSeries", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["addLogLevelToSeries"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "calculateLogsLabelStats", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["calculateLogsLabelStats"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogsParsers", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["LogsParsers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "calculateFieldStats", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["calculateFieldStats"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getParser", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["getParser"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parseLabels", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["parseLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findCommonLabels", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["findCommonLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findUniqueLabels", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["findUniqueLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "formatLabels", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["formatLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "objRemoveUndefined", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["objRemoveUndefined"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getActiveThreshold", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["getActiveThreshold"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sortThresholds", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["sortThresholds"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getMappedValue", function() { return _utils__WEBPACK_IMPORTED_MODULE_0__["getMappedValue"]; });

/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types */ "./packages/grafana-data/src/types/index.ts");
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _types__WEBPACK_IMPORTED_MODULE_1__) if(["Registry","deprecationWarning","CSVHeaderStyle","readCSV","CSVReader","toCSV","getLogLevel","getLogLevelFromKey","addLogLevelToSeries","calculateLogsLabelStats","LogsParsers","calculateFieldStats","getParser","parseLabels","findCommonLabels","findUniqueLabels","formatLabels","objRemoveUndefined","getActiveThreshold","sortThresholds","getMappedValue","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _types__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vector */ "./packages/grafana-data/src/vector/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AppendedVectors", function() { return _vector__WEBPACK_IMPORTED_MODULE_2__["AppendedVectors"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArrayVector", function() { return _vector__WEBPACK_IMPORTED_MODULE_2__["ArrayVector"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircularVector", function() { return _vector__WEBPACK_IMPORTED_MODULE_2__["CircularVector"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConstantVector", function() { return _vector__WEBPACK_IMPORTED_MODULE_2__["ConstantVector"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaledVector", function() { return _vector__WEBPACK_IMPORTED_MODULE_2__["ScaledVector"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SortedVector", function() { return _vector__WEBPACK_IMPORTED_MODULE_2__["SortedVector"]; });

/* harmony import */ var _dataframe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dataframe */ "./packages/grafana-data/src/dataframe/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataFrameView", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["DataFrameView"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldCache", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["FieldCache"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircularDataFrame", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["CircularDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MISSING_VALUE", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["MISSING_VALUE"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MutableDataFrame", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["MutableDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypeFromValue", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["guessFieldTypeFromValue"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypeForField", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["guessFieldTypeForField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "guessFieldTypes", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["guessFieldTypes"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isTableData", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["isTableData"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isDataFrame", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["isDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDataFrame", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["toDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toLegacyResponseData", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["toLegacyResponseData"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sortDataFrame", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["sortDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reverseDataFrame", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["reverseDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTimeField", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["getTimeField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDataFrameRow", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["getDataFrameRow"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDataFrameDTO", function() { return _dataframe__WEBPACK_IMPORTED_MODULE_3__["toDataFrameDTO"]; });

/* harmony import */ var _transformations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./transformations */ "./packages/grafana-data/src/transformations/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MatcherID", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["MatcherID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldMatcherID", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["FieldMatcherID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FrameMatcherID", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["FrameMatcherID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataTransformerID", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["DataTransformerID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fieldMatchers", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["fieldMatchers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "frameMatchers", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["frameMatchers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFieldMatcher", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["getFieldMatcher"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFrameMatchers", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["getFrameMatchers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformDataFrame", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["transformDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformersRegistry", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["transformersRegistry"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReduceTransformerOptions", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["ReduceTransformerOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilterFieldsByNameTransformerOptions", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["FilterFieldsByNameTransformerOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReducerID", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["ReducerID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reduceField", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["reduceField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fieldReducers", function() { return _transformations__WEBPACK_IMPORTED_MODULE_4__["fieldReducers"]; });

/* harmony import */ var _datetime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./datetime */ "./packages/grafana-data/src/datetime/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ISO_8601", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["ISO_8601"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setLocale", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["setLocale"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLocaleData", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["getLocaleData"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isDateTime", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["isDateTime"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toUtc", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["toUtc"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toDuration", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["toDuration"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTime", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["dateTime"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTimeAsMoment", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["dateTimeAsMoment"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateTimeForTimeZone", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["dateTimeForTimeZone"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTimeZoneGroups", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["getTimeZoneGroups"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dateMath", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["dateMath"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rangeUtil", function() { return _datetime__WEBPACK_IMPORTED_MODULE_5__["rangeUtil"]; });

/* harmony import */ var _text__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./text */ "./packages/grafana-data/src/text/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stringToJsRegex", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["stringToJsRegex"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stringToMs", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["stringToMs"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toNumberString", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["toNumberString"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toIntegerOrUndefined", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["toIntegerOrUndefined"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFloatOrUndefined", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["toFloatOrUndefined"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setMarkdownOptions", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["setMarkdownOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "renderMarkdown", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["renderMarkdown"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findHighlightChunksInText", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["findHighlightChunksInText"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findMatchesInText", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["findMatchesInText"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parseFlags", function() { return _text__WEBPACK_IMPORTED_MODULE_6__["parseFlags"]; });










/***/ }),

/***/ "./packages/grafana-data/src/text/index.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-data/src/text/index.ts ***!
  \*************************************************/
/*! exports provided: stringToJsRegex, stringToMs, toNumberString, toIntegerOrUndefined, toFloatOrUndefined, setMarkdownOptions, renderMarkdown, findHighlightChunksInText, findMatchesInText, parseFlags */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./string */ "./packages/grafana-data/src/text/string.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stringToJsRegex", function() { return _string__WEBPACK_IMPORTED_MODULE_0__["stringToJsRegex"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stringToMs", function() { return _string__WEBPACK_IMPORTED_MODULE_0__["stringToMs"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toNumberString", function() { return _string__WEBPACK_IMPORTED_MODULE_0__["toNumberString"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toIntegerOrUndefined", function() { return _string__WEBPACK_IMPORTED_MODULE_0__["toIntegerOrUndefined"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFloatOrUndefined", function() { return _string__WEBPACK_IMPORTED_MODULE_0__["toFloatOrUndefined"]; });

/* harmony import */ var _markdown__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./markdown */ "./packages/grafana-data/src/text/markdown.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setMarkdownOptions", function() { return _markdown__WEBPACK_IMPORTED_MODULE_1__["setMarkdownOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "renderMarkdown", function() { return _markdown__WEBPACK_IMPORTED_MODULE_1__["renderMarkdown"]; });

/* harmony import */ var _text__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./text */ "./packages/grafana-data/src/text/text.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findHighlightChunksInText", function() { return _text__WEBPACK_IMPORTED_MODULE_2__["findHighlightChunksInText"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findMatchesInText", function() { return _text__WEBPACK_IMPORTED_MODULE_2__["findMatchesInText"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parseFlags", function() { return _text__WEBPACK_IMPORTED_MODULE_2__["parseFlags"]; });






/***/ }),

/***/ "./packages/grafana-data/src/text/markdown.ts":
/*!****************************************************!*\
  !*** ./packages/grafana-data/src/text/markdown.ts ***!
  \****************************************************/
/*! exports provided: setMarkdownOptions, renderMarkdown */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMarkdownOptions", function() { return setMarkdownOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderMarkdown", function() { return renderMarkdown; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var marked__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! marked */ "./node_modules/marked/lib/marked.js");
/* harmony import */ var marked__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(marked__WEBPACK_IMPORTED_MODULE_1__);


var defaultMarkedOptions = {
    renderer: new marked__WEBPACK_IMPORTED_MODULE_1___default.a.Renderer(),
    pedantic: false,
    gfm: true,
    tables: true,
    sanitize: true,
    smartLists: true,
    smartypants: false,
    xhtml: false,
};
function setMarkdownOptions(optionsOverride) {
    marked__WEBPACK_IMPORTED_MODULE_1___default.a.setOptions(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaultMarkedOptions, optionsOverride));
}
function renderMarkdown(str) {
    return marked__WEBPACK_IMPORTED_MODULE_1___default()(str || '');
}


/***/ }),

/***/ "./packages/grafana-data/src/text/string.ts":
/*!**************************************************!*\
  !*** ./packages/grafana-data/src/text/string.ts ***!
  \**************************************************/
/*! exports provided: stringToJsRegex, stringToMs, toNumberString, toIntegerOrUndefined, toFloatOrUndefined */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringToJsRegex", function() { return stringToJsRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringToMs", function() { return stringToMs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toNumberString", function() { return toNumberString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toIntegerOrUndefined", function() { return toIntegerOrUndefined; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toFloatOrUndefined", function() { return toFloatOrUndefined; });
function stringToJsRegex(str) {
    if (str[0] !== '/') {
        return new RegExp('^' + str + '$');
    }
    var match = str.match(new RegExp('^/(.*?)/(g?i?m?y?)$'));
    if (!match) {
        throw new Error("'" + str + "' is not a valid regular expression.");
    }
    return new RegExp(match[1], match[2]);
}
function stringToMs(str) {
    if (!str) {
        return 0;
    }
    var nr = parseInt(str, 10);
    var unit = str.substr(String(nr).length);
    var s = 1000;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    switch (unit) {
        case 's':
            return nr * s;
        case 'm':
            return nr * m;
        case 'h':
            return nr * h;
        case 'd':
            return nr * d;
        default:
            if (!unit) {
                return isNaN(nr) ? 0 : nr;
            }
            throw new Error('Not supported unit: ' + unit);
    }
}
function toNumberString(value) {
    if (value !== null && value !== undefined && Number.isFinite(value)) {
        return value.toString();
    }
    return '';
}
function toIntegerOrUndefined(value) {
    if (!value) {
        return undefined;
    }
    var v = parseInt(value, 10);
    return isNaN(v) ? undefined : v;
}
function toFloatOrUndefined(value) {
    if (!value) {
        return undefined;
    }
    var v = parseFloat(value);
    return isNaN(v) ? undefined : v;
}


/***/ }),

/***/ "./packages/grafana-data/src/text/text.ts":
/*!************************************************!*\
  !*** ./packages/grafana-data/src/text/text.ts ***!
  \************************************************/
/*! exports provided: findHighlightChunksInText, findMatchesInText, parseFlags */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findHighlightChunksInText", function() { return findHighlightChunksInText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findMatchesInText", function() { return findMatchesInText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFlags", function() { return parseFlags; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

/**
 * Adapt findMatchesInText for react-highlight-words findChunks handler.
 * See https://github.com/bvaughn/react-highlight-words#props
 */
function findHighlightChunksInText(_a) {
    var searchWords = _a.searchWords, textToHighlight = _a.textToHighlight;
    return searchWords.reduce(function (acc, term) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](acc, findMatchesInText(textToHighlight, term)); }, []);
}
var cleanNeedle = function (needle) {
    return needle.replace(/[[{(][\w,.-?:*+]+$/, '');
};
/**
 * Returns a list of substring regexp matches.
 */
function findMatchesInText(haystack, needle) {
    // Empty search can send re.exec() into infinite loop, exit early
    if (!haystack || !needle) {
        return [];
    }
    var matches = [];
    var _a = parseFlags(cleanNeedle(needle)), cleaned = _a.cleaned, flags = _a.flags;
    var regexp;
    try {
        regexp = new RegExp("(?:" + cleaned + ")", flags);
    }
    catch (error) {
        return matches;
    }
    haystack.replace(regexp, function (substring) {
        var rest = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            rest[_i - 1] = arguments[_i];
        }
        if (substring) {
            var offset = rest[rest.length - 2];
            matches.push({
                text: substring,
                start: offset,
                length: substring.length,
                end: offset + substring.length,
            });
        }
        return '';
    });
    return matches;
}
var CLEAR_FLAG = '-';
var FLAGS_REGEXP = /\(\?([ims-]+)\)/g;
/**
 * Converts any mode modifers in the text to the Javascript equivalent flag
 */
function parseFlags(text) {
    var flags = new Set(['g']);
    var cleaned = text.replace(FLAGS_REGEXP, function (str, group) {
        var clearAll = group.startsWith(CLEAR_FLAG);
        for (var i = 0; i < group.length; ++i) {
            var flag = group.charAt(i);
            if (clearAll || group.charAt(i - 1) === CLEAR_FLAG) {
                flags.delete(flag);
            }
            else if (flag !== CLEAR_FLAG) {
                flags.add(flag);
            }
        }
        return ''; // Remove flag from text
    });
    return {
        cleaned: cleaned,
        flags: Array.from(flags).join(''),
    };
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/fieldReducer.ts":
/*!*******************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/fieldReducer.ts ***!
  \*******************************************************************/
/*! exports provided: ReducerID, reduceField, fieldReducers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReducerID", function() { return ReducerID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduceField", function() { return reduceField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fieldReducers", function() { return fieldReducers; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_isNumber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/isNumber */ "./node_modules/lodash/isNumber.js");
/* harmony import */ var lodash_isNumber__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_isNumber__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _types_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/index */ "./packages/grafana-data/src/types/index.ts");
/* harmony import */ var _utils_Registry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/Registry */ "./packages/grafana-data/src/utils/Registry.ts");

// Libraries



var ReducerID;
(function (ReducerID) {
    ReducerID["sum"] = "sum";
    ReducerID["max"] = "max";
    ReducerID["min"] = "min";
    ReducerID["logmin"] = "logmin";
    ReducerID["mean"] = "mean";
    ReducerID["last"] = "last";
    ReducerID["first"] = "first";
    ReducerID["count"] = "count";
    ReducerID["range"] = "range";
    ReducerID["diff"] = "diff";
    ReducerID["delta"] = "delta";
    ReducerID["step"] = "step";
    ReducerID["firstNotNull"] = "firstNotNull";
    ReducerID["lastNotNull"] = "lastNotNull";
    ReducerID["changeCount"] = "changeCount";
    ReducerID["distinctCount"] = "distinctCount";
    ReducerID["allIsZero"] = "allIsZero";
    ReducerID["allIsNull"] = "allIsNull";
})(ReducerID || (ReducerID = {}));
/**
 * @returns an object with a key for each selected stat
 */
function reduceField(options) {
    var e_1, _a, e_2, _b, e_3, _c;
    var field = options.field, reducers = options.reducers;
    if (!field || !reducers || reducers.length < 1) {
        return {};
    }
    if (field.calcs) {
        // Find the values we need to calculate
        var missing = [];
        try {
            for (var reducers_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](reducers), reducers_1_1 = reducers_1.next(); !reducers_1_1.done; reducers_1_1 = reducers_1.next()) {
                var s = reducers_1_1.value;
                if (!field.calcs.hasOwnProperty(s)) {
                    missing.push(s);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (reducers_1_1 && !reducers_1_1.done && (_a = reducers_1.return)) _a.call(reducers_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        if (missing.length < 1) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field.calcs);
        }
    }
    var queue = fieldReducers.list(reducers);
    // Return early for empty series
    // This lets the concrete implementations assume at least one row
    var data = field.values;
    if (data.length < 1) {
        var calcs = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field.calcs);
        try {
            for (var queue_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](queue), queue_1_1 = queue_1.next(); !queue_1_1.done; queue_1_1 = queue_1.next()) {
                var reducer = queue_1_1.value;
                calcs[reducer.id] = reducer.emptyInputResult !== null ? reducer.emptyInputResult : null;
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (queue_1_1 && !queue_1_1.done && (_b = queue_1.return)) _b.call(queue_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return (field.calcs = calcs);
    }
    var nullValueMode = field.config.nullValueMode;
    var ignoreNulls = nullValueMode === _types_index__WEBPACK_IMPORTED_MODULE_2__["NullValueMode"].Ignore;
    var nullAsZero = nullValueMode === _types_index__WEBPACK_IMPORTED_MODULE_2__["NullValueMode"].AsZero;
    // Avoid calculating all the standard stats if possible
    if (queue.length === 1 && queue[0].reduce) {
        var values_1 = queue[0].reduce(field, ignoreNulls, nullAsZero);
        field.calcs = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field.calcs, values_1);
        return values_1;
    }
    // For now everything can use the standard stats
    var values = doStandardCalcs(field, ignoreNulls, nullAsZero);
    try {
        for (var queue_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](queue), queue_2_1 = queue_2.next(); !queue_2_1.done; queue_2_1 = queue_2.next()) {
            var reducer = queue_2_1.value;
            if (!values.hasOwnProperty(reducer.id) && reducer.reduce) {
                values = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, values, reducer.reduce(field, ignoreNulls, nullAsZero));
            }
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (queue_2_1 && !queue_2_1.done && (_c = queue_2.return)) _c.call(queue_2);
        }
        finally { if (e_3) throw e_3.error; }
    }
    field.calcs = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field.calcs, values);
    return values;
}
// ------------------------------------------------------------------------------
//
//  No Exported symbols below here.
//
// ------------------------------------------------------------------------------
var fieldReducers = new _utils_Registry__WEBPACK_IMPORTED_MODULE_3__["Registry"](function () { return [
    {
        id: ReducerID.lastNotNull,
        name: 'Last (not null)',
        description: 'Last non-null value',
        standard: true,
        aliasIds: ['current'],
        reduce: calculateLastNotNull,
    },
    {
        id: ReducerID.last,
        name: 'Last',
        description: 'Last Value',
        standard: true,
        reduce: calculateLast,
    },
    { id: ReducerID.first, name: 'First', description: 'First Value', standard: true, reduce: calculateFirst },
    {
        id: ReducerID.firstNotNull,
        name: 'First (not null)',
        description: 'First non-null value',
        standard: true,
        reduce: calculateFirstNotNull,
    },
    { id: ReducerID.min, name: 'Min', description: 'Minimum Value', standard: true },
    { id: ReducerID.max, name: 'Max', description: 'Maximum Value', standard: true },
    { id: ReducerID.mean, name: 'Mean', description: 'Average Value', standard: true, aliasIds: ['avg'] },
    {
        id: ReducerID.sum,
        name: 'Total',
        description: 'The sum of all values',
        emptyInputResult: 0,
        standard: true,
        aliasIds: ['total'],
    },
    {
        id: ReducerID.count,
        name: 'Count',
        description: 'Number of values in response',
        emptyInputResult: 0,
        standard: true,
    },
    {
        id: ReducerID.range,
        name: 'Range',
        description: 'Difference between minimum and maximum values',
        standard: true,
    },
    {
        id: ReducerID.delta,
        name: 'Delta',
        description: 'Cumulative change in value',
        standard: true,
    },
    {
        id: ReducerID.step,
        name: 'Step',
        description: 'Minimum interval between values',
        standard: true,
    },
    {
        id: ReducerID.diff,
        name: 'Difference',
        description: 'Difference between first and last values',
        standard: true,
    },
    {
        id: ReducerID.logmin,
        name: 'Min (above zero)',
        description: 'Used for log min scale',
        standard: true,
    },
    {
        id: ReducerID.allIsZero,
        name: 'All Zeros',
        description: 'All values are zero',
        emptyInputResult: false,
        standard: true,
    },
    {
        id: ReducerID.allIsNull,
        name: 'All Nulls',
        description: 'All values are null',
        emptyInputResult: true,
        standard: true,
    },
    {
        id: ReducerID.changeCount,
        name: 'Change Count',
        description: 'Number of times the value changes',
        standard: false,
        reduce: calculateChangeCount,
    },
    {
        id: ReducerID.distinctCount,
        name: 'Distinct Count',
        description: 'Number of distinct values',
        standard: false,
        reduce: calculateDistinctCount,
    },
]; });
function doStandardCalcs(field, ignoreNulls, nullAsZero) {
    var calcs = {
        sum: 0,
        max: -Number.MAX_VALUE,
        min: Number.MAX_VALUE,
        logmin: Number.MAX_VALUE,
        mean: null,
        last: null,
        first: null,
        lastNotNull: null,
        firstNotNull: null,
        count: 0,
        nonNullCount: 0,
        allIsNull: true,
        allIsZero: true,
        range: null,
        diff: null,
        delta: 0,
        step: Number.MAX_VALUE,
        // Just used for calcutations -- not exposed as a stat
        previousDeltaUp: true,
    };
    var data = field.values;
    calcs.count = data.length;
    for (var i = 0; i < data.length; i++) {
        var currentValue = data.get(i);
        if (i === 0) {
            calcs.first = currentValue;
        }
        calcs.last = currentValue;
        if (currentValue === null) {
            if (ignoreNulls) {
                continue;
            }
            if (nullAsZero) {
                currentValue = 0;
            }
        }
        if (currentValue !== null && currentValue !== undefined) {
            var isFirst = calcs.firstNotNull === null;
            if (isFirst) {
                calcs.firstNotNull = currentValue;
            }
            if (lodash_isNumber__WEBPACK_IMPORTED_MODULE_1___default()(currentValue)) {
                calcs.sum += currentValue;
                calcs.allIsNull = false;
                calcs.nonNullCount++;
                if (!isFirst) {
                    var step = currentValue - calcs.lastNotNull;
                    if (calcs.step > step) {
                        calcs.step = step; // the minimum interval
                    }
                    if (calcs.lastNotNull > currentValue) {
                        // counter reset
                        calcs.previousDeltaUp = false;
                        if (i === data.length - 1) {
                            // reset on last
                            calcs.delta += currentValue;
                        }
                    }
                    else {
                        if (calcs.previousDeltaUp) {
                            calcs.delta += step; // normal increment
                        }
                        else {
                            calcs.delta += currentValue; // account for counter reset
                        }
                        calcs.previousDeltaUp = true;
                    }
                }
                if (currentValue > calcs.max) {
                    calcs.max = currentValue;
                }
                if (currentValue < calcs.min) {
                    calcs.min = currentValue;
                }
                if (currentValue < calcs.logmin && currentValue > 0) {
                    calcs.logmin = currentValue;
                }
            }
            if (currentValue !== 0) {
                calcs.allIsZero = false;
            }
            calcs.lastNotNull = currentValue;
        }
    }
    if (calcs.max === -Number.MAX_VALUE) {
        calcs.max = null;
    }
    if (calcs.min === Number.MAX_VALUE) {
        calcs.min = null;
    }
    if (calcs.step === Number.MAX_VALUE) {
        calcs.step = null;
    }
    if (calcs.nonNullCount > 0) {
        calcs.mean = calcs.sum / calcs.nonNullCount;
    }
    if (calcs.allIsNull) {
        calcs.allIsZero = false;
    }
    if (calcs.max !== null && calcs.min !== null) {
        calcs.range = calcs.max - calcs.min;
    }
    if (lodash_isNumber__WEBPACK_IMPORTED_MODULE_1___default()(calcs.firstNotNull) && lodash_isNumber__WEBPACK_IMPORTED_MODULE_1___default()(calcs.lastNotNull)) {
        calcs.diff = calcs.lastNotNull - calcs.firstNotNull;
    }
    return calcs;
}
function calculateFirst(field, ignoreNulls, nullAsZero) {
    return { first: field.values.get(0) };
}
function calculateFirstNotNull(field, ignoreNulls, nullAsZero) {
    var data = field.values;
    for (var idx = 0; idx < data.length; idx++) {
        var v = data.get(idx);
        if (v != null && v !== undefined) {
            return { firstNotNull: v };
        }
    }
    return { firstNotNull: null };
}
function calculateLast(field, ignoreNulls, nullAsZero) {
    var data = field.values;
    return { last: data.get(data.length - 1) };
}
function calculateLastNotNull(field, ignoreNulls, nullAsZero) {
    var data = field.values;
    var idx = data.length - 1;
    while (idx >= 0) {
        var v = data.get(idx--);
        if (v != null && v !== undefined) {
            return { lastNotNull: v };
        }
    }
    return { lastNotNull: null };
}
function calculateChangeCount(field, ignoreNulls, nullAsZero) {
    var data = field.values;
    var count = 0;
    var first = true;
    var last = null;
    for (var i = 0; i < data.length; i++) {
        var currentValue = data.get(i);
        if (currentValue === null) {
            if (ignoreNulls) {
                continue;
            }
            if (nullAsZero) {
                currentValue = 0;
            }
        }
        if (!first && last !== currentValue) {
            count++;
        }
        first = false;
        last = currentValue;
    }
    return { changeCount: count };
}
function calculateDistinctCount(field, ignoreNulls, nullAsZero) {
    var data = field.values;
    var distinct = new Set();
    for (var i = 0; i < data.length; i++) {
        var currentValue = data.get(i);
        if (currentValue === null) {
            if (ignoreNulls) {
                continue;
            }
            if (nullAsZero) {
                currentValue = 0;
            }
        }
        distinct.add(currentValue);
    }
    return { distinctCount: distinct.size };
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/index.ts":
/*!************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/index.ts ***!
  \************************************************************/
/*! exports provided: MatcherID, FieldMatcherID, FrameMatcherID, DataTransformerID, fieldMatchers, frameMatchers, getFieldMatcher, getFrameMatchers, transformDataFrame, transformersRegistry, ReduceTransformerOptions, FilterFieldsByNameTransformerOptions, ReducerID, reduceField, fieldReducers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _matchers_ids__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./matchers/ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MatcherID", function() { return _matchers_ids__WEBPACK_IMPORTED_MODULE_0__["MatcherID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldMatcherID", function() { return _matchers_ids__WEBPACK_IMPORTED_MODULE_0__["FieldMatcherID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FrameMatcherID", function() { return _matchers_ids__WEBPACK_IMPORTED_MODULE_0__["FrameMatcherID"]; });

/* harmony import */ var _transformers_ids__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./transformers/ids */ "./packages/grafana-data/src/transformations/transformers/ids.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataTransformerID", function() { return _transformers_ids__WEBPACK_IMPORTED_MODULE_1__["DataTransformerID"]; });

/* harmony import */ var _matchers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./matchers */ "./packages/grafana-data/src/transformations/matchers.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fieldMatchers", function() { return _matchers__WEBPACK_IMPORTED_MODULE_2__["fieldMatchers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "frameMatchers", function() { return _matchers__WEBPACK_IMPORTED_MODULE_2__["frameMatchers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFieldMatcher", function() { return _matchers__WEBPACK_IMPORTED_MODULE_2__["getFieldMatcher"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFrameMatchers", function() { return _matchers__WEBPACK_IMPORTED_MODULE_2__["getFrameMatchers"]; });

/* harmony import */ var _transformers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./transformers */ "./packages/grafana-data/src/transformations/transformers.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformDataFrame", function() { return _transformers__WEBPACK_IMPORTED_MODULE_3__["transformDataFrame"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformersRegistry", function() { return _transformers__WEBPACK_IMPORTED_MODULE_3__["transformersRegistry"]; });

/* harmony import */ var _fieldReducer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fieldReducer */ "./packages/grafana-data/src/transformations/fieldReducer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReducerID", function() { return _fieldReducer__WEBPACK_IMPORTED_MODULE_4__["ReducerID"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reduceField", function() { return _fieldReducer__WEBPACK_IMPORTED_MODULE_4__["reduceField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fieldReducers", function() { return _fieldReducer__WEBPACK_IMPORTED_MODULE_4__["fieldReducers"]; });

/* harmony import */ var _transformers_filterByName__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./transformers/filterByName */ "./packages/grafana-data/src/transformations/transformers/filterByName.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilterFieldsByNameTransformerOptions", function() { return _transformers_filterByName__WEBPACK_IMPORTED_MODULE_5__["FilterFieldsByNameTransformerOptions"]; });

/* harmony import */ var _transformers_reduce__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./transformers/reduce */ "./packages/grafana-data/src/transformations/transformers/reduce.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReduceTransformerOptions", function() { return _transformers_reduce__WEBPACK_IMPORTED_MODULE_6__["ReduceTransformerOptions"]; });










/***/ }),

/***/ "./packages/grafana-data/src/transformations/matchers.ts":
/*!***************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/matchers.ts ***!
  \***************************************************************/
/*! exports provided: fieldMatchers, frameMatchers, getFieldMatcher, getFrameMatchers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fieldMatchers", function() { return fieldMatchers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frameMatchers", function() { return frameMatchers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldMatcher", function() { return getFieldMatcher; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameMatchers", function() { return getFrameMatchers; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _matchers_predicates__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./matchers/predicates */ "./packages/grafana-data/src/transformations/matchers/predicates.ts");
/* harmony import */ var _matchers_nameMatcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./matchers/nameMatcher */ "./packages/grafana-data/src/transformations/matchers/nameMatcher.ts");
/* harmony import */ var _matchers_fieldTypeMatcher__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./matchers/fieldTypeMatcher */ "./packages/grafana-data/src/transformations/matchers/fieldTypeMatcher.ts");
/* harmony import */ var _matchers_refIdMatcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./matchers/refIdMatcher */ "./packages/grafana-data/src/transformations/matchers/refIdMatcher.ts");
/* harmony import */ var _utils_Registry__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/Registry */ "./packages/grafana-data/src/utils/Registry.ts");

// Load the Buildtin matchers





var fieldMatchers = new _utils_Registry__WEBPACK_IMPORTED_MODULE_5__["Registry"](function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](Object(_matchers_predicates__WEBPACK_IMPORTED_MODULE_1__["getFieldPredicateMatchers"])(), Object(_matchers_fieldTypeMatcher__WEBPACK_IMPORTED_MODULE_3__["getFieldTypeMatchers"])(), Object(_matchers_nameMatcher__WEBPACK_IMPORTED_MODULE_2__["getFieldNameMatchers"])());
});
var frameMatchers = new _utils_Registry__WEBPACK_IMPORTED_MODULE_5__["Registry"](function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](Object(_matchers_predicates__WEBPACK_IMPORTED_MODULE_1__["getFramePredicateMatchers"])(), Object(_matchers_nameMatcher__WEBPACK_IMPORTED_MODULE_2__["getFrameNameMatchers"])(), Object(_matchers_refIdMatcher__WEBPACK_IMPORTED_MODULE_4__["getRefIdMatchers"])());
});
function getFieldMatcher(config) {
    var info = fieldMatchers.get(config.id);
    if (!info) {
        throw new Error('Unknown Matcher: ' + config.id);
    }
    return info.get(config.options);
}
function getFrameMatchers(config) {
    var info = frameMatchers.get(config.id);
    if (!info) {
        throw new Error('Unknown Matcher: ' + config.id);
    }
    return info.get(config.options);
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/matchers/fieldTypeMatcher.ts":
/*!********************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/matchers/fieldTypeMatcher.ts ***!
  \********************************************************************************/
/*! exports provided: getFieldTypeMatchers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldTypeMatchers", function() { return getFieldTypeMatchers; });
/* harmony import */ var _types_dataFrame__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../types/dataFrame */ "./packages/grafana-data/src/types/dataFrame.ts");
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");


// General Field matcher
var fieldTypeMacher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["FieldMatcherID"].byType,
    name: 'Field Type',
    description: 'match based on the field type',
    defaultOptions: _types_dataFrame__WEBPACK_IMPORTED_MODULE_0__["FieldType"].number,
    get: function (type) {
        return function (field) {
            return type === field.type;
        };
    },
    getOptionsDisplayText: function (type) {
        return "Field type: " + type;
    },
};
// Numeric Field matcher
// This gets its own entry so it shows up in the dropdown
var numericMacher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["FieldMatcherID"].numeric,
    name: 'Numeric Fields',
    description: 'Fields with type number',
    get: function () {
        return fieldTypeMacher.get(_types_dataFrame__WEBPACK_IMPORTED_MODULE_0__["FieldType"].number);
    },
    getOptionsDisplayText: function () {
        return 'Numeric Fields';
    },
};
// Time Field matcher
var timeMacher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["FieldMatcherID"].time,
    name: 'Time Fields',
    description: 'Fields with type time',
    get: function () {
        return fieldTypeMacher.get(_types_dataFrame__WEBPACK_IMPORTED_MODULE_0__["FieldType"].time);
    },
    getOptionsDisplayText: function () {
        return 'Time Fields';
    },
};
/**
 * Registry Initalization
 */
function getFieldTypeMatchers() {
    return [fieldTypeMacher, numericMacher, timeMacher];
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/matchers/ids.ts":
/*!*******************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/matchers/ids.ts ***!
  \*******************************************************************/
/*! exports provided: MatcherID, FieldMatcherID, FrameMatcherID */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MatcherID", function() { return MatcherID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FieldMatcherID", function() { return FieldMatcherID; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrameMatcherID", function() { return FrameMatcherID; });
// This needs to be in its own file to avoid circular references
// Builtin Predicates
// not using 'any' and 'never' since they are reservered keywords
var MatcherID;
(function (MatcherID) {
    MatcherID["anyMatch"] = "anyMatch";
    MatcherID["allMatch"] = "allMatch";
    MatcherID["invertMatch"] = "invertMatch";
    MatcherID["alwaysMatch"] = "alwaysMatch";
    MatcherID["neverMatch"] = "neverMatch";
})(MatcherID || (MatcherID = {}));
var FieldMatcherID;
(function (FieldMatcherID) {
    // Specific Types
    FieldMatcherID["numeric"] = "numeric";
    FieldMatcherID["time"] = "time";
    // With arguments
    FieldMatcherID["byType"] = "byType";
    FieldMatcherID["byName"] = "byName";
    // byIndex = 'byIndex',
    // byLabel = 'byLabel',
})(FieldMatcherID || (FieldMatcherID = {}));
/**
 * Field name matchers
 */
var FrameMatcherID;
(function (FrameMatcherID) {
    FrameMatcherID["byName"] = "byName";
    FrameMatcherID["byRefId"] = "byRefId";
    FrameMatcherID["byIndex"] = "byIndex";
    FrameMatcherID["byLabel"] = "byLabel";
})(FrameMatcherID || (FrameMatcherID = {}));


/***/ }),

/***/ "./packages/grafana-data/src/transformations/matchers/nameMatcher.ts":
/*!***************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/matchers/nameMatcher.ts ***!
  \***************************************************************************/
/*! exports provided: getFieldNameMatchers, getFrameNameMatchers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldNameMatchers", function() { return getFieldNameMatchers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameNameMatchers", function() { return getFrameNameMatchers; });
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");
/* harmony import */ var _text_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../text/string */ "./packages/grafana-data/src/text/string.ts");


// General Field matcher
var fieldNameMacher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_0__["FieldMatcherID"].byName,
    name: 'Field Name',
    description: 'match the field name',
    defaultOptions: '/.*/',
    get: function (pattern) {
        var regex = Object(_text_string__WEBPACK_IMPORTED_MODULE_1__["stringToJsRegex"])(pattern);
        return function (field) {
            return regex.test(field.name);
        };
    },
    getOptionsDisplayText: function (pattern) {
        return "Field name: " + pattern;
    },
};
// General Field matcher
var frameNameMacher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_0__["FrameMatcherID"].byName,
    name: 'Frame Name',
    description: 'match the frame name',
    defaultOptions: '/.*/',
    get: function (pattern) {
        var regex = Object(_text_string__WEBPACK_IMPORTED_MODULE_1__["stringToJsRegex"])(pattern);
        return function (frame) {
            return regex.test(frame.name || '');
        };
    },
    getOptionsDisplayText: function (pattern) {
        return "Frame name: " + pattern;
    },
};
/**
 * Registry Initalization
 */
function getFieldNameMatchers() {
    return [fieldNameMacher];
}
function getFrameNameMatchers() {
    return [frameNameMacher];
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/matchers/predicates.ts":
/*!**************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/matchers/predicates.ts ***!
  \**************************************************************************/
/*! exports provided: alwaysFieldMatcher, alwaysFrameMatcher, neverFieldMatcher, neverFrameMatcher, getFieldPredicateMatchers, getFramePredicateMatchers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alwaysFieldMatcher", function() { return alwaysFieldMatcher; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alwaysFrameMatcher", function() { return alwaysFrameMatcher; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "neverFieldMatcher", function() { return neverFieldMatcher; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "neverFrameMatcher", function() { return neverFrameMatcher; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldPredicateMatchers", function() { return getFieldPredicateMatchers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFramePredicateMatchers", function() { return getFramePredicateMatchers; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");
/* harmony import */ var _matchers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../matchers */ "./packages/grafana-data/src/transformations/matchers.ts");



var anyFieldMatcher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].anyMatch,
    name: 'Any',
    description: 'Any child matches (OR)',
    excludeFromPicker: true,
    defaultOptions: [],
    get: function (options) {
        var children = options.map(function (option) {
            return Object(_matchers__WEBPACK_IMPORTED_MODULE_2__["getFieldMatcher"])(option);
        });
        return function (field) {
            var e_1, _a;
            try {
                for (var children_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](children), children_1_1 = children_1.next(); !children_1_1.done; children_1_1 = children_1.next()) {
                    var child = children_1_1.value;
                    if (child(field)) {
                        return true;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (children_1_1 && !children_1_1.done && (_a = children_1.return)) _a.call(children_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return false;
        };
    },
    getOptionsDisplayText: function (options) {
        var e_2, _a;
        var text = '';
        try {
            for (var options_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](options), options_1_1 = options_1.next(); !options_1_1.done; options_1_1 = options_1.next()) {
                var sub = options_1_1.value;
                if (text.length > 0) {
                    text += ' OR ';
                }
                var matcher = _matchers__WEBPACK_IMPORTED_MODULE_2__["fieldMatchers"].get(sub.id);
                text += matcher.getOptionsDisplayText ? matcher.getOptionsDisplayText(sub) : matcher.name;
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (options_1_1 && !options_1_1.done && (_a = options_1.return)) _a.call(options_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return text;
    },
};
var anyFrameMatcher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].anyMatch,
    name: 'Any',
    description: 'Any child matches (OR)',
    excludeFromPicker: true,
    defaultOptions: [],
    get: function (options) {
        var children = options.map(function (option) {
            return Object(_matchers__WEBPACK_IMPORTED_MODULE_2__["getFrameMatchers"])(option);
        });
        return function (frame) {
            var e_3, _a;
            try {
                for (var children_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](children), children_2_1 = children_2.next(); !children_2_1.done; children_2_1 = children_2.next()) {
                    var child = children_2_1.value;
                    if (child(frame)) {
                        return true;
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (children_2_1 && !children_2_1.done && (_a = children_2.return)) _a.call(children_2);
                }
                finally { if (e_3) throw e_3.error; }
            }
            return false;
        };
    },
    getOptionsDisplayText: function (options) {
        var e_4, _a;
        var text = '';
        try {
            for (var options_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](options), options_2_1 = options_2.next(); !options_2_1.done; options_2_1 = options_2.next()) {
                var sub = options_2_1.value;
                if (text.length > 0) {
                    text += ' OR ';
                }
                var matcher = _matchers__WEBPACK_IMPORTED_MODULE_2__["frameMatchers"].get(sub.id);
                text += matcher.getOptionsDisplayText ? matcher.getOptionsDisplayText(sub) : matcher.name;
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (options_2_1 && !options_2_1.done && (_a = options_2.return)) _a.call(options_2);
            }
            finally { if (e_4) throw e_4.error; }
        }
        return text;
    },
};
var allFieldsMatcher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].allMatch,
    name: 'All',
    description: 'Everything matches (AND)',
    excludeFromPicker: true,
    defaultOptions: [],
    get: function (options) {
        var children = options.map(function (option) {
            return Object(_matchers__WEBPACK_IMPORTED_MODULE_2__["getFieldMatcher"])(option);
        });
        return function (field) {
            var e_5, _a;
            try {
                for (var children_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](children), children_3_1 = children_3.next(); !children_3_1.done; children_3_1 = children_3.next()) {
                    var child = children_3_1.value;
                    if (!child(field)) {
                        return false;
                    }
                }
            }
            catch (e_5_1) { e_5 = { error: e_5_1 }; }
            finally {
                try {
                    if (children_3_1 && !children_3_1.done && (_a = children_3.return)) _a.call(children_3);
                }
                finally { if (e_5) throw e_5.error; }
            }
            return true;
        };
    },
    getOptionsDisplayText: function (options) {
        var e_6, _a;
        var text = '';
        try {
            for (var options_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](options), options_3_1 = options_3.next(); !options_3_1.done; options_3_1 = options_3.next()) {
                var sub = options_3_1.value;
                if (text.length > 0) {
                    text += ' AND ';
                }
                var matcher = _matchers__WEBPACK_IMPORTED_MODULE_2__["fieldMatchers"].get(sub.id); // Ugho what about frame
                text += matcher.getOptionsDisplayText ? matcher.getOptionsDisplayText(sub) : matcher.name;
            }
        }
        catch (e_6_1) { e_6 = { error: e_6_1 }; }
        finally {
            try {
                if (options_3_1 && !options_3_1.done && (_a = options_3.return)) _a.call(options_3);
            }
            finally { if (e_6) throw e_6.error; }
        }
        return text;
    },
};
var allFramesMatcher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].allMatch,
    name: 'All',
    description: 'Everything matches (AND)',
    excludeFromPicker: true,
    defaultOptions: [],
    get: function (options) {
        var children = options.map(function (option) {
            return Object(_matchers__WEBPACK_IMPORTED_MODULE_2__["getFrameMatchers"])(option);
        });
        return function (frame) {
            var e_7, _a;
            try {
                for (var children_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](children), children_4_1 = children_4.next(); !children_4_1.done; children_4_1 = children_4.next()) {
                    var child = children_4_1.value;
                    if (!child(frame)) {
                        return false;
                    }
                }
            }
            catch (e_7_1) { e_7 = { error: e_7_1 }; }
            finally {
                try {
                    if (children_4_1 && !children_4_1.done && (_a = children_4.return)) _a.call(children_4);
                }
                finally { if (e_7) throw e_7.error; }
            }
            return true;
        };
    },
    getOptionsDisplayText: function (options) {
        var e_8, _a;
        var text = '';
        try {
            for (var options_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](options), options_4_1 = options_4.next(); !options_4_1.done; options_4_1 = options_4.next()) {
                var sub = options_4_1.value;
                if (text.length > 0) {
                    text += ' AND ';
                }
                var matcher = _matchers__WEBPACK_IMPORTED_MODULE_2__["frameMatchers"].get(sub.id);
                text += matcher.getOptionsDisplayText ? matcher.getOptionsDisplayText(sub) : matcher.name;
            }
        }
        catch (e_8_1) { e_8 = { error: e_8_1 }; }
        finally {
            try {
                if (options_4_1 && !options_4_1.done && (_a = options_4.return)) _a.call(options_4);
            }
            finally { if (e_8) throw e_8.error; }
        }
        return text;
    },
};
var notFieldMatcher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].invertMatch,
    name: 'NOT',
    description: 'Inverts other matchers',
    excludeFromPicker: true,
    get: function (option) {
        var check = Object(_matchers__WEBPACK_IMPORTED_MODULE_2__["getFieldMatcher"])(option);
        return function (field) {
            return !check(field);
        };
    },
    getOptionsDisplayText: function (options) {
        var matcher = _matchers__WEBPACK_IMPORTED_MODULE_2__["fieldMatchers"].get(options.id);
        var text = matcher.getOptionsDisplayText ? matcher.getOptionsDisplayText(options.options) : matcher.name;
        return 'NOT ' + text;
    },
};
var notFrameMatcher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].invertMatch,
    name: 'NOT',
    description: 'Inverts other matchers',
    excludeFromPicker: true,
    get: function (option) {
        var check = Object(_matchers__WEBPACK_IMPORTED_MODULE_2__["getFrameMatchers"])(option);
        return function (frame) {
            return !check(frame);
        };
    },
    getOptionsDisplayText: function (options) {
        var matcher = _matchers__WEBPACK_IMPORTED_MODULE_2__["frameMatchers"].get(options.id);
        var text = matcher.getOptionsDisplayText ? matcher.getOptionsDisplayText(options.options) : matcher.name;
        return 'NOT ' + text;
    },
};
var alwaysFieldMatcher = function (field) {
    return true;
};
var alwaysFrameMatcher = function (frame) {
    return true;
};
var neverFieldMatcher = function (field) {
    return false;
};
var neverFrameMatcher = function (frame) {
    return false;
};
var alwaysFieldMatcherInfo = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].alwaysMatch,
    name: 'All Fields',
    description: 'Always Match',
    get: function (option) {
        return alwaysFieldMatcher;
    },
    getOptionsDisplayText: function (options) {
        return 'Always';
    },
};
var alwaysFrameMatcherInfo = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].alwaysMatch,
    name: 'All Frames',
    description: 'Always Match',
    get: function (option) {
        return alwaysFrameMatcher;
    },
    getOptionsDisplayText: function (options) {
        return 'Always';
    },
};
var neverFieldMatcherInfo = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].neverMatch,
    name: 'No Fields',
    description: 'Never Match',
    excludeFromPicker: true,
    get: function (option) {
        return neverFieldMatcher;
    },
    getOptionsDisplayText: function (options) {
        return 'Never';
    },
};
var neverFrameMatcherInfo = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["MatcherID"].neverMatch,
    name: 'No Frames',
    description: 'Never Match',
    get: function (option) {
        return neverFrameMatcher;
    },
    getOptionsDisplayText: function (options) {
        return 'Never';
    },
};
function getFieldPredicateMatchers() {
    return [anyFieldMatcher, allFieldsMatcher, notFieldMatcher, alwaysFieldMatcherInfo, neverFieldMatcherInfo];
}
function getFramePredicateMatchers() {
    return [anyFrameMatcher, allFramesMatcher, notFrameMatcher, alwaysFrameMatcherInfo, neverFrameMatcherInfo];
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/matchers/refIdMatcher.ts":
/*!****************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/matchers/refIdMatcher.ts ***!
  \****************************************************************************/
/*! exports provided: getRefIdMatchers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRefIdMatchers", function() { return getRefIdMatchers; });
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");

// General Field matcher
var refIdMacher = {
    id: _ids__WEBPACK_IMPORTED_MODULE_0__["FrameMatcherID"].byRefId,
    name: 'Query refId',
    description: 'match the refId',
    defaultOptions: 'A',
    get: function (pattern) {
        return function (frame) {
            return pattern === frame.refId;
        };
    },
    getOptionsDisplayText: function (pattern) {
        return "RefID: " + pattern;
    },
};
function getRefIdMatchers() {
    return [refIdMacher];
}


/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers.ts":
/*!*******************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers.ts ***!
  \*******************************************************************/
/*! exports provided: transformDataFrame, transformersRegistry, ReduceTransformerOptions, FilterFieldsByNameTransformerOptions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformDataFrame", function() { return transformDataFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformersRegistry", function() { return transformersRegistry; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _utils_Registry__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/Registry */ "./packages/grafana-data/src/utils/Registry.ts");
/* harmony import */ var _transformers_append__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./transformers/append */ "./packages/grafana-data/src/transformations/transformers/append.ts");
/* harmony import */ var _transformers_reduce__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./transformers/reduce */ "./packages/grafana-data/src/transformations/transformers/reduce.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReduceTransformerOptions", function() { return _transformers_reduce__WEBPACK_IMPORTED_MODULE_3__["ReduceTransformerOptions"]; });

/* harmony import */ var _transformers_filter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./transformers/filter */ "./packages/grafana-data/src/transformations/transformers/filter.ts");
/* harmony import */ var _transformers_filterByName__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./transformers/filterByName */ "./packages/grafana-data/src/transformations/transformers/filterByName.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilterFieldsByNameTransformerOptions", function() { return _transformers_filterByName__WEBPACK_IMPORTED_MODULE_5__["FilterFieldsByNameTransformerOptions"]; });

/* harmony import */ var _transformers_noop__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./transformers/noop */ "./packages/grafana-data/src/transformations/transformers/noop.ts");


// Initalize the Registry





/**
 * Apply configured transformations to the input data
 */
function transformDataFrame(options, data) {
    var e_1, _a, e_2, _b;
    var processed = data;
    try {
        for (var options_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](options), options_1_1 = options_1.next(); !options_1_1.done; options_1_1 = options_1.next()) {
            var config = options_1_1.value;
            var info = transformersRegistry.get(config.id);
            var transformer = info.transformer(config.options);
            var after = transformer(processed);
            // Add a key to the metadata if the data changed
            if (after && after !== processed) {
                try {
                    for (var after_1 = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](after)), after_1_1 = after_1.next(); !after_1_1.done; after_1_1 = after_1.next()) {
                        var series = after_1_1.value;
                        if (!series.meta) {
                            series.meta = {};
                        }
                        if (!series.meta.transformations) {
                            series.meta.transformations = [info.id];
                        }
                        else {
                            series.meta.transformations = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](series.meta.transformations, [info.id]);
                        }
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (after_1_1 && !after_1_1.done && (_b = after_1.return)) _b.call(after_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                processed = after;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (options_1_1 && !options_1_1.done && (_a = options_1.return)) _a.call(options_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return processed;
}
/**
 * Registry of transformation options that can be driven by
 * stored configuration files.
 */
var TransformerRegistry = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TransformerRegistry, _super);
    function TransformerRegistry() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    // ------------------------------------------------------------
    // Nacent options for more functional programming
    // The API to these functions should change to match the actual
    // needs of people trying to use it.
    //  filterFields|Frames is left off since it is likely easier to
    //  support with `frames.filter( f => {...} )`
    // ------------------------------------------------------------
    TransformerRegistry.prototype.append = function (data, options) {
        return _transformers_append__WEBPACK_IMPORTED_MODULE_2__["appendTransformer"].transformer(options || _transformers_append__WEBPACK_IMPORTED_MODULE_2__["appendTransformer"].defaultOptions)(data)[0];
    };
    TransformerRegistry.prototype.reduce = function (data, options) {
        return _transformers_reduce__WEBPACK_IMPORTED_MODULE_3__["reduceTransformer"].transformer(options)(data);
    };
    return TransformerRegistry;
}(_utils_Registry__WEBPACK_IMPORTED_MODULE_1__["Registry"]));
var transformersRegistry = new TransformerRegistry(function () { return [
    _transformers_noop__WEBPACK_IMPORTED_MODULE_6__["noopTransformer"],
    _transformers_filter__WEBPACK_IMPORTED_MODULE_4__["filterFieldsTransformer"],
    _transformers_filterByName__WEBPACK_IMPORTED_MODULE_5__["filterFieldsByNameTransformer"],
    _transformers_filter__WEBPACK_IMPORTED_MODULE_4__["filterFramesTransformer"],
    _transformers_append__WEBPACK_IMPORTED_MODULE_2__["appendTransformer"],
    _transformers_reduce__WEBPACK_IMPORTED_MODULE_3__["reduceTransformer"],
]; });



/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers/append.ts":
/*!**************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers/append.ts ***!
  \**************************************************************************/
/*! exports provided: appendTransformer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendTransformer", function() { return appendTransformer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/transformers/ids.ts");
/* harmony import */ var _dataframe_MutableDataFrame__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../dataframe/MutableDataFrame */ "./packages/grafana-data/src/dataframe/MutableDataFrame.ts");



var appendTransformer = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["DataTransformerID"].append,
    name: 'Append',
    description: 'Append values into a single DataFrame.  This uses the name as the key',
    defaultOptions: {},
    /**
     * Return a modified copy of the series.  If the transform is not or should not
     * be applied, just return the input series
     */
    transformer: function (options) {
        return function (data) {
            var e_1, _a;
            if (data.length < 2) {
                return data;
            }
            // Add the first row
            var processed = new _dataframe_MutableDataFrame__WEBPACK_IMPORTED_MODULE_2__["MutableDataFrame"]();
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data[0].fields), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var f = _c.value;
                    processed.addField(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, f, { values: tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](f.values.toArray()) }));
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            for (var i = 1; i < data.length; i++) {
                var frame = data[i];
                var startLength = frame.length;
                for (var j = 0; j < frame.fields.length; j++) {
                    var src = frame.fields[j];
                    var vals = processed.values[src.name];
                    if (!vals) {
                        vals = processed.addField(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, src, { values: [] }), startLength).values;
                    }
                    // Add each row
                    for (var k = 0; k < frame.length; k++) {
                        vals.add(src.values.get(k));
                    }
                }
                processed.validate();
            }
            return [processed];
        };
    },
};


/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers/filter.ts":
/*!**************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers/filter.ts ***!
  \**************************************************************************/
/*! exports provided: filterFieldsTransformer, filterFramesTransformer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterFieldsTransformer", function() { return filterFieldsTransformer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterFramesTransformer", function() { return filterFramesTransformer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./noop */ "./packages/grafana-data/src/transformations/transformers/noop.ts");
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/transformers/ids.ts");
/* harmony import */ var _matchers_ids__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../matchers/ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");
/* harmony import */ var _matchers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../matchers */ "./packages/grafana-data/src/transformations/matchers.ts");





var filterFieldsTransformer = {
    id: _ids__WEBPACK_IMPORTED_MODULE_2__["DataTransformerID"].filterFields,
    name: 'Filter Fields',
    description: 'select a subset of fields',
    defaultOptions: {
        include: { id: _matchers_ids__WEBPACK_IMPORTED_MODULE_3__["FieldMatcherID"].numeric },
    },
    /**
     * Return a modified copy of the series.  If the transform is not or should not
     * be applied, just return the input series
     */
    transformer: function (options) {
        if (!options.include && !options.exclude) {
            return _noop__WEBPACK_IMPORTED_MODULE_1__["noopTransformer"].transformer({});
        }
        var include = options.include ? Object(_matchers__WEBPACK_IMPORTED_MODULE_4__["getFieldMatcher"])(options.include) : null;
        var exclude = options.exclude ? Object(_matchers__WEBPACK_IMPORTED_MODULE_4__["getFieldMatcher"])(options.exclude) : null;
        return function (data) {
            var e_1, _a;
            var processed = [];
            try {
                for (var data_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
                    var series = data_1_1.value;
                    // Find the matching field indexes
                    var fields = [];
                    for (var i = 0; i < series.fields.length; i++) {
                        var field = series.fields[i];
                        if (exclude) {
                            if (exclude(field)) {
                                continue;
                            }
                            if (!include) {
                                fields.push(field);
                            }
                        }
                        if (include && include(field)) {
                            fields.push(field);
                        }
                    }
                    if (!fields.length) {
                        continue;
                    }
                    var copy = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { // all the other properties
                        fields: fields });
                    processed.push(copy);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return processed;
        };
    },
};
var filterFramesTransformer = {
    id: _ids__WEBPACK_IMPORTED_MODULE_2__["DataTransformerID"].filterFrames,
    name: 'Filter Frames',
    description: 'select a subset of frames',
    defaultOptions: {},
    /**
     * Return a modified copy of the series.  If the transform is not or should not
     * be applied, just return the input series
     */
    transformer: function (options) {
        if (!options.include && !options.exclude) {
            return _noop__WEBPACK_IMPORTED_MODULE_1__["noopTransformer"].transformer({});
        }
        var include = options.include ? Object(_matchers__WEBPACK_IMPORTED_MODULE_4__["getFrameMatchers"])(options.include) : null;
        var exclude = options.exclude ? Object(_matchers__WEBPACK_IMPORTED_MODULE_4__["getFrameMatchers"])(options.exclude) : null;
        return function (data) {
            var e_2, _a;
            var processed = [];
            try {
                for (var data_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data), data_2_1 = data_2.next(); !data_2_1.done; data_2_1 = data_2.next()) {
                    var series = data_2_1.value;
                    if (exclude) {
                        if (exclude(series)) {
                            continue;
                        }
                        if (!include) {
                            processed.push(series);
                        }
                    }
                    if (include && include(series)) {
                        processed.push(series);
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (data_2_1 && !data_2_1.done && (_a = data_2.return)) _a.call(data_2);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return processed;
        };
    },
};


/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers/filterByName.ts":
/*!********************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers/filterByName.ts ***!
  \********************************************************************************/
/*! exports provided: filterFieldsByNameTransformer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterFieldsByNameTransformer", function() { return filterFieldsByNameTransformer; });
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/transformers/ids.ts");
/* harmony import */ var _filter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./filter */ "./packages/grafana-data/src/transformations/transformers/filter.ts");
/* harmony import */ var _matchers_ids__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../matchers/ids */ "./packages/grafana-data/src/transformations/matchers/ids.ts");



var filterFieldsByNameTransformer = {
    id: _ids__WEBPACK_IMPORTED_MODULE_0__["DataTransformerID"].filterFieldsByName,
    name: 'Filter fields by name',
    description: 'select a subset of fields',
    defaultOptions: {},
    /**
     * Return a modified copy of the series.  If the transform is not or should not
     * be applied, just return the input series
     */
    transformer: function (options) {
        var filterOptions = {};
        if (options.include) {
            filterOptions.include = {
                id: _matchers_ids__WEBPACK_IMPORTED_MODULE_2__["FieldMatcherID"].byName,
                options: options.include,
            };
        }
        if (options.exclude) {
            filterOptions.exclude = {
                id: _matchers_ids__WEBPACK_IMPORTED_MODULE_2__["FieldMatcherID"].byName,
                options: options.exclude,
            };
        }
        return _filter__WEBPACK_IMPORTED_MODULE_1__["filterFieldsTransformer"].transformer(filterOptions);
    },
};


/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers/ids.ts":
/*!***********************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers/ids.ts ***!
  \***********************************************************************/
/*! exports provided: DataTransformerID */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataTransformerID", function() { return DataTransformerID; });
var DataTransformerID;
(function (DataTransformerID) {
    //  join = 'join', // Pick a field and merge all series based on that field
    DataTransformerID["append"] = "append";
    //  rotate = 'rotate', // Columns to rows
    DataTransformerID["reduce"] = "reduce";
    DataTransformerID["filterFields"] = "filterFields";
    DataTransformerID["filterFieldsByName"] = "filterFieldsByName";
    DataTransformerID["filterFrames"] = "filterFrames";
    DataTransformerID["noop"] = "noop";
})(DataTransformerID || (DataTransformerID = {}));


/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers/noop.ts":
/*!************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers/noop.ts ***!
  \************************************************************************/
/*! exports provided: noopTransformer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "noopTransformer", function() { return noopTransformer; });
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/transformers/ids.ts");

var noopTransformer = {
    id: _ids__WEBPACK_IMPORTED_MODULE_0__["DataTransformerID"].noop,
    name: 'noop',
    description: 'No-operation transformer',
    defaultOptions: {},
    /**
     * Return a modified copy of the series.  If the transform is not or should not
     * be applied, just return the input series
     */
    transformer: function (options) {
        return function (data) { return data; };
    },
};


/***/ }),

/***/ "./packages/grafana-data/src/transformations/transformers/reduce.ts":
/*!**************************************************************************!*\
  !*** ./packages/grafana-data/src/transformations/transformers/reduce.ts ***!
  \**************************************************************************/
/*! exports provided: reduceTransformer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduceTransformer", function() { return reduceTransformer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _ids__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ids */ "./packages/grafana-data/src/transformations/transformers/ids.ts");
/* harmony import */ var _fieldReducer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../fieldReducer */ "./packages/grafana-data/src/transformations/fieldReducer.ts");
/* harmony import */ var _matchers_predicates__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../matchers/predicates */ "./packages/grafana-data/src/transformations/matchers/predicates.ts");
/* harmony import */ var _types_dataFrame__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../types/dataFrame */ "./packages/grafana-data/src/types/dataFrame.ts");
/* harmony import */ var _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../vector/ArrayVector */ "./packages/grafana-data/src/vector/ArrayVector.ts");
/* harmony import */ var _dataframe_processDataFrame__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../dataframe/processDataFrame */ "./packages/grafana-data/src/dataframe/processDataFrame.ts");
/* harmony import */ var _matchers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../matchers */ "./packages/grafana-data/src/transformations/matchers.ts");








var reduceTransformer = {
    id: _ids__WEBPACK_IMPORTED_MODULE_1__["DataTransformerID"].reduce,
    name: 'Reducer',
    description: 'Return a DataFrame with the reduction results',
    defaultOptions: {
        reducers: [_fieldReducer__WEBPACK_IMPORTED_MODULE_2__["ReducerID"].min, _fieldReducer__WEBPACK_IMPORTED_MODULE_2__["ReducerID"].max, _fieldReducer__WEBPACK_IMPORTED_MODULE_2__["ReducerID"].mean, _fieldReducer__WEBPACK_IMPORTED_MODULE_2__["ReducerID"].last],
    },
    /**
     * Return a modified copy of the series.  If the transform is not or should not
     * be applied, just return the input series
     */
    transformer: function (options) {
        var matcher = options.fields ? Object(_matchers__WEBPACK_IMPORTED_MODULE_7__["getFieldMatcher"])(options.fields) : _matchers_predicates__WEBPACK_IMPORTED_MODULE_3__["alwaysFieldMatcher"];
        var calculators = options.reducers && options.reducers.length ? _fieldReducer__WEBPACK_IMPORTED_MODULE_2__["fieldReducers"].list(options.reducers) : [];
        var reducers = calculators.map(function (c) { return c.id; });
        return function (data) {
            var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
            var processed = [];
            try {
                for (var data_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
                    var series = data_1_1.value;
                    var values = [];
                    var fields = [];
                    var byId = {};
                    values.push(new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_5__["ArrayVector"]()); // The name
                    fields.push({
                        name: 'Field',
                        type: _types_dataFrame__WEBPACK_IMPORTED_MODULE_4__["FieldType"].string,
                        values: values[0],
                        config: {},
                    });
                    try {
                        for (var calculators_1 = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](calculators)), calculators_1_1 = calculators_1.next(); !calculators_1_1.done; calculators_1_1 = calculators_1.next()) {
                            var info = calculators_1_1.value;
                            var vals = new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_5__["ArrayVector"]();
                            byId[info.id] = vals;
                            values.push(vals);
                            fields.push({
                                name: info.id,
                                type: _types_dataFrame__WEBPACK_IMPORTED_MODULE_4__["FieldType"].other,
                                values: values[values.length - 1],
                                config: {
                                    title: info.name,
                                },
                            });
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (calculators_1_1 && !calculators_1_1.done && (_b = calculators_1.return)) _b.call(calculators_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                    for (var i = 0; i < series.fields.length; i++) {
                        var field = series.fields[i];
                        if (matcher(field)) {
                            var results = Object(_fieldReducer__WEBPACK_IMPORTED_MODULE_2__["reduceField"])({
                                field: field,
                                reducers: reducers,
                            });
                            // Update the name list
                            values[0].buffer.push(field.name);
                            try {
                                for (var calculators_2 = (e_3 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](calculators)), calculators_2_1 = calculators_2.next(); !calculators_2_1.done; calculators_2_1 = calculators_2.next()) {
                                    var info = calculators_2_1.value;
                                    var v = results[info.id];
                                    byId[info.id].buffer.push(v);
                                }
                            }
                            catch (e_3_1) { e_3 = { error: e_3_1 }; }
                            finally {
                                try {
                                    if (calculators_2_1 && !calculators_2_1.done && (_c = calculators_2.return)) _c.call(calculators_2);
                                }
                                finally { if (e_3) throw e_3.error; }
                            }
                        }
                    }
                    try {
                        for (var fields_1 = (e_4 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](fields)), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
                            var f = fields_1_1.value;
                            var t = Object(_dataframe_processDataFrame__WEBPACK_IMPORTED_MODULE_6__["guessFieldTypeForField"])(f);
                            if (t) {
                                f.type = t;
                            }
                        }
                    }
                    catch (e_4_1) { e_4 = { error: e_4_1 }; }
                    finally {
                        try {
                            if (fields_1_1 && !fields_1_1.done && (_d = fields_1.return)) _d.call(fields_1);
                        }
                        finally { if (e_4) throw e_4.error; }
                    }
                    processed.push(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { // Same properties, different fields
                        fields: fields, length: values[0].length }));
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return processed;
        };
    },
};


/***/ }),

/***/ "./packages/grafana-data/src/types/ScopedVars.ts":
/*!*******************************************************!*\
  !*** ./packages/grafana-data/src/types/ScopedVars.ts ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/data.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-data/src/types/data.ts ***!
  \*************************************************/
/*! exports provided: LoadingState, NullValueMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadingState", function() { return LoadingState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullValueMode", function() { return NullValueMode; });
var LoadingState;
(function (LoadingState) {
    LoadingState["NotStarted"] = "NotStarted";
    LoadingState["Loading"] = "Loading";
    LoadingState["Streaming"] = "Streaming";
    LoadingState["Done"] = "Done";
    LoadingState["Error"] = "Error";
})(LoadingState || (LoadingState = {}));
var NullValueMode;
(function (NullValueMode) {
    NullValueMode["Null"] = "null";
    NullValueMode["Ignore"] = "connected";
    NullValueMode["AsZero"] = "null as zero";
})(NullValueMode || (NullValueMode = {}));


/***/ }),

/***/ "./packages/grafana-data/src/types/dataFrame.ts":
/*!******************************************************!*\
  !*** ./packages/grafana-data/src/types/dataFrame.ts ***!
  \******************************************************/
/*! exports provided: FieldType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FieldType", function() { return FieldType; });
var FieldType;
(function (FieldType) {
    FieldType["time"] = "time";
    FieldType["number"] = "number";
    FieldType["string"] = "string";
    FieldType["boolean"] = "boolean";
    FieldType["other"] = "other";
})(FieldType || (FieldType = {}));


/***/ }),

/***/ "./packages/grafana-data/src/types/dataLink.ts":
/*!*****************************************************!*\
  !*** ./packages/grafana-data/src/types/dataLink.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/displayValue.ts":
/*!*********************************************************!*\
  !*** ./packages/grafana-data/src/types/displayValue.ts ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/graph.ts":
/*!**************************************************!*\
  !*** ./packages/grafana-data/src/types/graph.ts ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/index.ts":
/*!**************************************************!*\
  !*** ./packages/grafana-data/src/types/index.ts ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./data */ "./packages/grafana-data/src/types/data.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoadingState", function() { return _data__WEBPACK_IMPORTED_MODULE_0__["LoadingState"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullValueMode", function() { return _data__WEBPACK_IMPORTED_MODULE_0__["NullValueMode"]; });

/* harmony import */ var _dataFrame__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dataFrame */ "./packages/grafana-data/src/types/dataFrame.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldType", function() { return _dataFrame__WEBPACK_IMPORTED_MODULE_1__["FieldType"]; });

/* harmony import */ var _dataLink__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dataLink */ "./packages/grafana-data/src/types/dataLink.ts");
/* harmony import */ var _dataLink__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_dataLink__WEBPACK_IMPORTED_MODULE_2__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _dataLink__WEBPACK_IMPORTED_MODULE_2__) if(["LoadingState","NullValueMode","FieldType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _dataLink__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _logs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./logs */ "./packages/grafana-data/src/types/logs.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["LogLevel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogsMetaKind", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["LogsMetaKind"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogsDedupStrategy", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogsDedupDescription", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["LogsDedupDescription"]; });

/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./navModel */ "./packages/grafana-data/src/types/navModel.ts");
/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_navModel__WEBPACK_IMPORTED_MODULE_4__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _navModel__WEBPACK_IMPORTED_MODULE_4__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _navModel__WEBPACK_IMPORTED_MODULE_4__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _select__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./select */ "./packages/grafana-data/src/types/select.ts");
/* harmony import */ var _select__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_select__WEBPACK_IMPORTED_MODULE_5__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _select__WEBPACK_IMPORTED_MODULE_5__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _select__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _time__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./time */ "./packages/grafana-data/src/types/time.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultTimeZone", function() { return _time__WEBPACK_IMPORTED_MODULE_6__["DefaultTimeZone"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TIME_FORMAT", function() { return _time__WEBPACK_IMPORTED_MODULE_6__["TIME_FORMAT"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultTimeRange", function() { return _time__WEBPACK_IMPORTED_MODULE_6__["DefaultTimeRange"]; });

/* harmony import */ var _threshold__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./threshold */ "./packages/grafana-data/src/types/threshold.ts");
/* harmony import */ var _threshold__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_threshold__WEBPACK_IMPORTED_MODULE_7__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _threshold__WEBPACK_IMPORTED_MODULE_7__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _threshold__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils */ "./packages/grafana-data/src/types/utils.ts");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils__WEBPACK_IMPORTED_MODULE_8__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _utils__WEBPACK_IMPORTED_MODULE_8__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _utils__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _valueMapping__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./valueMapping */ "./packages/grafana-data/src/types/valueMapping.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MappingType", function() { return _valueMapping__WEBPACK_IMPORTED_MODULE_9__["MappingType"]; });

/* harmony import */ var _displayValue__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./displayValue */ "./packages/grafana-data/src/types/displayValue.ts");
/* harmony import */ var _displayValue__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_displayValue__WEBPACK_IMPORTED_MODULE_10__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _displayValue__WEBPACK_IMPORTED_MODULE_10__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","MappingType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _displayValue__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _graph__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./graph */ "./packages/grafana-data/src/types/graph.ts");
/* harmony import */ var _graph__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_graph__WEBPACK_IMPORTED_MODULE_11__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _graph__WEBPACK_IMPORTED_MODULE_11__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","MappingType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _graph__WEBPACK_IMPORTED_MODULE_11__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _ScopedVars__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./ScopedVars */ "./packages/grafana-data/src/types/ScopedVars.ts");
/* harmony import */ var _ScopedVars__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_ScopedVars__WEBPACK_IMPORTED_MODULE_12__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _ScopedVars__WEBPACK_IMPORTED_MODULE_12__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","MappingType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _ScopedVars__WEBPACK_IMPORTED_MODULE_12__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _transformations__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./transformations */ "./packages/grafana-data/src/types/transformations.ts");
/* harmony import */ var _transformations__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_transformations__WEBPACK_IMPORTED_MODULE_13__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _transformations__WEBPACK_IMPORTED_MODULE_13__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","MappingType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _transformations__WEBPACK_IMPORTED_MODULE_13__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _vector__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./vector */ "./packages/grafana-data/src/types/vector.ts");
/* harmony import */ var _vector__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_vector__WEBPACK_IMPORTED_MODULE_14__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _vector__WEBPACK_IMPORTED_MODULE_14__) if(["LoadingState","NullValueMode","FieldType","LogLevel","LogsMetaKind","LogsDedupStrategy","LogsDedupDescription","DefaultTimeZone","TIME_FORMAT","DefaultTimeRange","MappingType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _vector__WEBPACK_IMPORTED_MODULE_14__[key]; }) }(__WEBPACK_IMPORT_KEY__));

















/***/ }),

/***/ "./packages/grafana-data/src/types/logs.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-data/src/types/logs.ts ***!
  \*************************************************/
/*! exports provided: LogLevel, LogsMetaKind, LogsDedupStrategy, LogsDedupDescription */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLevel", function() { return LogLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogsMetaKind", function() { return LogsMetaKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogsDedupStrategy", function() { return LogsDedupStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogsDedupDescription", function() { return LogsDedupDescription; });
/**
 * Mapping of log level abbreviation to canonical log level.
 * Supported levels are reduce to limit color variation.
 */
var LogLevel;
(function (LogLevel) {
    LogLevel["emerg"] = "critical";
    LogLevel["alert"] = "critical";
    LogLevel["crit"] = "critical";
    LogLevel["critical"] = "critical";
    LogLevel["warn"] = "warning";
    LogLevel["warning"] = "warning";
    LogLevel["err"] = "error";
    LogLevel["eror"] = "error";
    LogLevel["error"] = "error";
    LogLevel["info"] = "info";
    LogLevel["notice"] = "info";
    LogLevel["dbug"] = "debug";
    LogLevel["debug"] = "debug";
    LogLevel["trace"] = "trace";
    LogLevel["unknown"] = "unknown";
})(LogLevel || (LogLevel = {}));
var LogsMetaKind;
(function (LogsMetaKind) {
    LogsMetaKind[LogsMetaKind["Number"] = 0] = "Number";
    LogsMetaKind[LogsMetaKind["String"] = 1] = "String";
    LogsMetaKind[LogsMetaKind["LabelsMap"] = 2] = "LabelsMap";
})(LogsMetaKind || (LogsMetaKind = {}));
var LogsDedupStrategy;
(function (LogsDedupStrategy) {
    LogsDedupStrategy["none"] = "none";
    LogsDedupStrategy["exact"] = "exact";
    LogsDedupStrategy["numbers"] = "numbers";
    LogsDedupStrategy["signature"] = "signature";
})(LogsDedupStrategy || (LogsDedupStrategy = {}));
var LogsDedupDescription;
(function (LogsDedupDescription) {
    LogsDedupDescription["none"] = "No de-duplication";
    LogsDedupDescription["exact"] = "De-duplication of successive lines that are identical, ignoring ISO datetimes.";
    LogsDedupDescription["numbers"] = "De-duplication of successive lines that are identical when ignoring numbers, e.g., IP addresses, latencies.";
    LogsDedupDescription["signature"] = "De-duplication of successive lines that have identical punctuation and whitespace.";
})(LogsDedupDescription || (LogsDedupDescription = {}));


/***/ }),

/***/ "./packages/grafana-data/src/types/navModel.ts":
/*!*****************************************************!*\
  !*** ./packages/grafana-data/src/types/navModel.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/select.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-data/src/types/select.ts ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/threshold.ts":
/*!******************************************************!*\
  !*** ./packages/grafana-data/src/types/threshold.ts ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/time.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-data/src/types/time.ts ***!
  \*************************************************/
/*! exports provided: DefaultTimeZone, TIME_FORMAT, DefaultTimeRange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultTimeZone", function() { return DefaultTimeZone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TIME_FORMAT", function() { return TIME_FORMAT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultTimeRange", function() { return DefaultTimeRange; });
var DefaultTimeZone = 'browser';
var TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
var DefaultTimeRange = {
    from: {},
    to: {},
    raw: { from: '6h', to: 'now' },
};


/***/ }),

/***/ "./packages/grafana-data/src/types/transformations.ts":
/*!************************************************************!*\
  !*** ./packages/grafana-data/src/types/transformations.ts ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/utils.ts":
/*!**************************************************!*\
  !*** ./packages/grafana-data/src/types/utils.ts ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/types/valueMapping.ts":
/*!*********************************************************!*\
  !*** ./packages/grafana-data/src/types/valueMapping.ts ***!
  \*********************************************************/
/*! exports provided: MappingType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MappingType", function() { return MappingType; });
var MappingType;
(function (MappingType) {
    MappingType[MappingType["ValueToText"] = 1] = "ValueToText";
    MappingType[MappingType["RangeToText"] = 2] = "RangeToText";
})(MappingType || (MappingType = {}));


/***/ }),

/***/ "./packages/grafana-data/src/types/vector.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-data/src/types/vector.ts ***!
  \***************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-data/src/utils/Registry.ts":
/*!*****************************************************!*\
  !*** ./packages/grafana-data/src/utils/Registry.ts ***!
  \*****************************************************/
/*! exports provided: Registry */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Registry", function() { return Registry; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

var Registry = /** @class */ (function () {
    function Registry(init) {
        this.init = init;
        this.ordered = [];
        this.byId = new Map();
        this.initalized = false;
    }
    Registry.prototype.getIfExists = function (id) {
        var e_1, _a;
        if (!this.initalized) {
            if (this.init) {
                try {
                    for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.init()), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var ext = _c.value;
                        this.register(ext);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
            this.sort();
            this.initalized = true;
        }
        if (id) {
            return this.byId.get(id);
        }
        return undefined;
    };
    Registry.prototype.get = function (id) {
        var v = this.getIfExists(id);
        if (!v) {
            throw new Error('Undefined: ' + id);
        }
        return v;
    };
    Registry.prototype.selectOptions = function (current, filter) {
        var e_2, _a, e_3, _b;
        if (!this.initalized) {
            this.getIfExists('xxx'); // will trigger init
        }
        var select = {
            options: [],
            current: [],
        };
        var currentIds = {};
        if (current) {
            try {
                for (var current_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](current), current_1_1 = current_1.next(); !current_1_1.done; current_1_1 = current_1.next()) {
                    var id = current_1_1.value;
                    currentIds[id] = true;
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (current_1_1 && !current_1_1.done && (_a = current_1.return)) _a.call(current_1);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.ordered), _d = _c.next(); !_d.done; _d = _c.next()) {
                var ext = _d.value;
                if (ext.excludeFromPicker) {
                    continue;
                }
                if (filter && !filter(ext)) {
                    continue;
                }
                var option = {
                    value: ext.id,
                    label: ext.name,
                    description: ext.description,
                };
                select.options.push(option);
                if (currentIds[ext.id]) {
                    select.current.push(option);
                }
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
            }
            finally { if (e_3) throw e_3.error; }
        }
        return select;
    };
    /**
     * Return a list of values by ID, or all values if not specified
     */
    Registry.prototype.list = function (ids) {
        var e_4, _a;
        if (ids) {
            var found = [];
            try {
                for (var ids_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](ids), ids_1_1 = ids_1.next(); !ids_1_1.done; ids_1_1 = ids_1.next()) {
                    var id = ids_1_1.value;
                    var v = this.getIfExists(id);
                    if (v) {
                        found.push(v);
                    }
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (ids_1_1 && !ids_1_1.done && (_a = ids_1.return)) _a.call(ids_1);
                }
                finally { if (e_4) throw e_4.error; }
            }
            return found;
        }
        if (!this.initalized) {
            this.getIfExists('xxx'); // will trigger init
        }
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](this.ordered); // copy of everythign just in case
    };
    Registry.prototype.register = function (ext) {
        var e_5, _a;
        if (this.byId.has(ext.id)) {
            throw new Error('Duplicate Key:' + ext.id);
        }
        this.byId.set(ext.id, ext);
        this.ordered.push(ext);
        if (ext.aliasIds) {
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](ext.aliasIds), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var alias = _c.value;
                    if (!this.byId.has(alias)) {
                        this.byId.set(alias, ext);
                    }
                }
            }
            catch (e_5_1) { e_5 = { error: e_5_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_5) throw e_5.error; }
            }
        }
        if (this.initalized) {
            this.sort();
        }
    };
    Registry.prototype.sort = function () {
        // TODO sort the list
    };
    return Registry;
}());



/***/ }),

/***/ "./packages/grafana-data/src/utils/csv.ts":
/*!************************************************!*\
  !*** ./packages/grafana-data/src/utils/csv.ts ***!
  \************************************************/
/*! exports provided: CSVHeaderStyle, readCSV, CSVReader, toCSV */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CSVHeaderStyle", function() { return CSVHeaderStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readCSV", function() { return readCSV; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CSVReader", function() { return CSVReader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toCSV", function() { return toCSV; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var papaparse__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! papaparse */ "./node_modules/papaparse/papaparse.min.js");
/* harmony import */ var papaparse__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(papaparse__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_defaults__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/defaults */ "./node_modules/lodash/defaults.js");
/* harmony import */ var lodash_defaults__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_defaults__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_isNumber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/isNumber */ "./node_modules/lodash/isNumber.js");
/* harmony import */ var lodash_isNumber__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_isNumber__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../types */ "./packages/grafana-data/src/types/index.ts");
/* harmony import */ var _dataframe_processDataFrame__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../dataframe/processDataFrame */ "./packages/grafana-data/src/dataframe/processDataFrame.ts");
/* harmony import */ var _dataframe_MutableDataFrame__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../dataframe/MutableDataFrame */ "./packages/grafana-data/src/dataframe/MutableDataFrame.ts");

// Libraries



// Types



var CSVHeaderStyle;
(function (CSVHeaderStyle) {
    CSVHeaderStyle[CSVHeaderStyle["full"] = 0] = "full";
    CSVHeaderStyle[CSVHeaderStyle["name"] = 1] = "name";
    CSVHeaderStyle[CSVHeaderStyle["none"] = 2] = "none";
})(CSVHeaderStyle || (CSVHeaderStyle = {}));
function readCSV(csv, options) {
    return new CSVReader(options).readCSV(csv);
}
var ParseState;
(function (ParseState) {
    ParseState[ParseState["Starting"] = 0] = "Starting";
    ParseState[ParseState["InHeader"] = 1] = "InHeader";
    ParseState[ParseState["ReadingRows"] = 2] = "ReadingRows";
})(ParseState || (ParseState = {}));
var CSVReader = /** @class */ (function () {
    function CSVReader(options) {
        var _this = this;
        // PapaParse callback on each line
        this.step = function (results, parser) {
            var e_1, _a;
            for (var i = 0; i < results.data.length; i++) {
                var line = results.data[i];
                if (line.length < 1) {
                    continue;
                }
                var first = line[0]; // null or value, papaparse does not return ''
                if (first) {
                    // Comment or header queue
                    if (first.startsWith('#')) {
                        // Look for special header column
                        // #{columkey}#a,b,c
                        var idx = first.indexOf('#', 2);
                        if (idx > 0) {
                            var k = first.substr(1, idx - 1);
                            var isName = 'name' === k;
                            // Simple object used to check if headers match
                            var headerKeys = {
                                unit: '#',
                            };
                            // Check if it is a known/supported column
                            if (isName || headerKeys.hasOwnProperty(k)) {
                                // Starting a new table after reading rows
                                if (_this.state === ParseState.ReadingRows) {
                                    _this.current = new _dataframe_MutableDataFrame__WEBPACK_IMPORTED_MODULE_6__["MutableDataFrame"]({ fields: [] });
                                    _this.data.push(_this.current);
                                }
                                var v = first.substr(idx + 1);
                                if (isName) {
                                    _this.current.addFieldFor(undefined, v);
                                    for (var j = 1; j < line.length; j++) {
                                        _this.current.addFieldFor(undefined, line[j]);
                                    }
                                }
                                else {
                                    var fields = _this.current.fields;
                                    for (var j = 0; j < fields.length; j++) {
                                        if (!fields[j].config) {
                                            fields[j].config = {};
                                        }
                                        var disp = fields[j].config; // any lets name lookup
                                        disp[k] = j === 0 ? v : line[j];
                                    }
                                }
                                _this.state = ParseState.InHeader;
                                continue;
                            }
                        }
                        else if (_this.state === ParseState.Starting) {
                            _this.state = ParseState.InHeader;
                            continue;
                        }
                        // Ignore comment lines
                        continue;
                    }
                    if (_this.state === ParseState.Starting) {
                        var type = Object(_dataframe_processDataFrame__WEBPACK_IMPORTED_MODULE_5__["guessFieldTypeFromValue"])(first);
                        if (type === _types__WEBPACK_IMPORTED_MODULE_4__["FieldType"].string) {
                            try {
                                for (var line_1 = (e_1 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](line)), line_1_1 = line_1.next(); !line_1_1.done; line_1_1 = line_1.next()) {
                                    var s = line_1_1.value;
                                    _this.current.addFieldFor(undefined, s);
                                }
                            }
                            catch (e_1_1) { e_1 = { error: e_1_1 }; }
                            finally {
                                try {
                                    if (line_1_1 && !line_1_1.done && (_a = line_1.return)) _a.call(line_1);
                                }
                                finally { if (e_1) throw e_1.error; }
                            }
                            _this.state = ParseState.InHeader;
                            continue;
                        }
                        _this.state = ParseState.InHeader; // fall through to read rows
                    }
                }
                // Add the current results to the data
                if (_this.state !== ParseState.ReadingRows) {
                    // anything???
                }
                _this.state = ParseState.ReadingRows;
                // Make sure colum structure is valid
                if (line.length > _this.current.fields.length) {
                    var fields = _this.current.fields;
                    for (var f = fields.length; f < line.length; f++) {
                        _this.current.addFieldFor(line[f]);
                    }
                    if (_this.callback) {
                        _this.callback.onHeader(_this.current.fields);
                    }
                }
                _this.current.appendRow(line);
                if (_this.callback) {
                    // // Send the header after we guess the type
                    // if (this.series.rows.length === 0) {
                    //   this.callback.onHeader(this.series);
                    // }
                    _this.callback.onRow(line);
                }
            }
        };
        if (!options) {
            options = {};
        }
        this.config = options.config || {};
        this.callback = options.callback;
        this.current = new _dataframe_MutableDataFrame__WEBPACK_IMPORTED_MODULE_6__["MutableDataFrame"]({ fields: [] });
        this.state = ParseState.Starting;
        this.data = [];
    }
    CSVReader.prototype.readCSV = function (text) {
        this.current = new _dataframe_MutableDataFrame__WEBPACK_IMPORTED_MODULE_6__["MutableDataFrame"]({ fields: [] });
        this.data = [this.current];
        var papacfg = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.config, { dynamicTyping: false, skipEmptyLines: true, comments: false, step: this.step });
        papaparse__WEBPACK_IMPORTED_MODULE_1___default.a.parse(text, papacfg);
        return this.data;
    };
    return CSVReader;
}());

function writeValue(value, config) {
    var str = value.toString();
    if (str.includes('"')) {
        // Escape the double quote characters
        return config.quoteChar + str.replace(/"/gi, '""') + config.quoteChar;
    }
    if (str.includes('\n') || str.includes(config.delimiter)) {
        return config.quoteChar + str + config.quoteChar;
    }
    return str;
}
function makeFieldWriter(field, config) {
    if (field.type) {
        if (field.type === _types__WEBPACK_IMPORTED_MODULE_4__["FieldType"].boolean) {
            return function (value) {
                return value ? 'true' : 'false';
            };
        }
        if (field.type === _types__WEBPACK_IMPORTED_MODULE_4__["FieldType"].number) {
            return function (value) {
                if (lodash_isNumber__WEBPACK_IMPORTED_MODULE_3___default()(value)) {
                    return value.toString();
                }
                return writeValue(value, config);
            };
        }
    }
    return function (value) { return writeValue(value, config); };
}
function getHeaderLine(key, fields, config) {
    var e_2, _a;
    var isName = 'name' === key;
    var isType = 'type' === key;
    try {
        for (var fields_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](fields), fields_1_1 = fields_1.next(); !fields_1_1.done; fields_1_1 = fields_1.next()) {
            var f = fields_1_1.value;
            var display = f.config;
            if (isName || isType || (display && display.hasOwnProperty(key))) {
                var line = '#' + key + '#';
                for (var i = 0; i < fields.length; i++) {
                    if (i > 0) {
                        line = line + config.delimiter;
                    }
                    var v = fields[i].name;
                    if (isType) {
                        v = fields[i].type;
                    }
                    else if (isName) {
                        // already name
                    }
                    else {
                        v = fields[i].config[key];
                    }
                    if (v) {
                        line = line + writeValue(v, config);
                    }
                }
                return line + config.newline;
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (fields_1_1 && !fields_1_1.done && (_a = fields_1.return)) _a.call(fields_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return '';
}
function toCSV(data, config) {
    var e_3, _a;
    if (!data) {
        return '';
    }
    var csv = '';
    config = lodash_defaults__WEBPACK_IMPORTED_MODULE_2___default()(config, {
        delimiter: ',',
        newline: '\r\n',
        quoteChar: '"',
        encoding: '',
        headerStyle: CSVHeaderStyle.name,
    });
    try {
        for (var data_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
            var series = data_1_1.value;
            var fields = series.fields;
            if (config.headerStyle === CSVHeaderStyle.full) {
                csv =
                    csv +
                        getHeaderLine('name', fields, config) +
                        getHeaderLine('type', fields, config) +
                        getHeaderLine('unit', fields, config) +
                        getHeaderLine('dateFormat', fields, config);
            }
            else if (config.headerStyle === CSVHeaderStyle.name) {
                for (var i = 0; i < fields.length; i++) {
                    if (i > 0) {
                        csv += config.delimiter;
                    }
                    csv += fields[i].name;
                }
                csv += config.newline;
            }
            var length = fields[0].values.length;
            if (length > 0) {
                var writers = fields.map(function (field) { return makeFieldWriter(field, config); });
                for (var i = 0; i < length; i++) {
                    for (var j = 0; j < fields.length; j++) {
                        if (j > 0) {
                            csv = csv + config.delimiter;
                        }
                        var v = fields[j].values.get(i);
                        if (v !== null) {
                            csv = csv + writers[j](v);
                        }
                    }
                    csv = csv + config.newline;
                }
            }
            csv = csv + config.newline;
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
        }
        finally { if (e_3) throw e_3.error; }
    }
    return csv;
}


/***/ }),

/***/ "./packages/grafana-data/src/utils/deprecationWarning.ts":
/*!***************************************************************!*\
  !*** ./packages/grafana-data/src/utils/deprecationWarning.ts ***!
  \***************************************************************/
/*! exports provided: deprecationWarning */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deprecationWarning", function() { return deprecationWarning; });
// Avoid writing the warning message more than once every 10s
var history = {};
var deprecationWarning = function (file, oldName, newName) {
    var message = "[Deprecation warning] " + file + ": " + oldName + " is deprecated";
    if (newName) {
        message += ".  Use " + newName + " instead";
    }
    var now = Date.now();
    var last = history[message];
    if (!last || now - last > 10000) {
        console.warn(message);
        history[message] = now;
    }
};


/***/ }),

/***/ "./packages/grafana-data/src/utils/fieldParser.ts":
/*!********************************************************!*\
  !*** ./packages/grafana-data/src/utils/fieldParser.ts ***!
  \********************************************************/
/*! exports provided: makeFieldParser */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeFieldParser", function() { return makeFieldParser; });
/* harmony import */ var _types_dataFrame__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/dataFrame */ "./packages/grafana-data/src/types/dataFrame.ts");
/* harmony import */ var _dataframe_processDataFrame__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dataframe/processDataFrame */ "./packages/grafana-data/src/dataframe/processDataFrame.ts");


function makeFieldParser(value, field) {
    if (!field.type) {
        if (field.name === 'time' || field.name === 'Time') {
            field.type = _types_dataFrame__WEBPACK_IMPORTED_MODULE_0__["FieldType"].time;
        }
        else {
            field.type = Object(_dataframe_processDataFrame__WEBPACK_IMPORTED_MODULE_1__["guessFieldTypeFromValue"])(value);
        }
    }
    if (field.type === _types_dataFrame__WEBPACK_IMPORTED_MODULE_0__["FieldType"].number) {
        return function (value) {
            return parseFloat(value);
        };
    }
    // Will convert anything that starts with "T" to true
    if (field.type === _types_dataFrame__WEBPACK_IMPORTED_MODULE_0__["FieldType"].boolean) {
        return function (value) {
            return !(value[0] === 'F' || value[0] === 'f' || value[0] === '0');
        };
    }
    // Just pass the string back
    return function (value) { return value; };
}


/***/ }),

/***/ "./packages/grafana-data/src/utils/index.ts":
/*!**************************************************!*\
  !*** ./packages/grafana-data/src/utils/index.ts ***!
  \**************************************************/
/*! exports provided: Registry, deprecationWarning, CSVHeaderStyle, readCSV, CSVReader, toCSV, getLogLevel, getLogLevelFromKey, addLogLevelToSeries, calculateLogsLabelStats, LogsParsers, calculateFieldStats, getParser, parseLabels, findCommonLabels, findUniqueLabels, formatLabels, objRemoveUndefined, getActiveThreshold, sortThresholds, getMappedValue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Registry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Registry */ "./packages/grafana-data/src/utils/Registry.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registry", function() { return _Registry__WEBPACK_IMPORTED_MODULE_0__["Registry"]; });

/* harmony import */ var _deprecationWarning__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./deprecationWarning */ "./packages/grafana-data/src/utils/deprecationWarning.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "deprecationWarning", function() { return _deprecationWarning__WEBPACK_IMPORTED_MODULE_1__["deprecationWarning"]; });

/* harmony import */ var _csv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./csv */ "./packages/grafana-data/src/utils/csv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSVHeaderStyle", function() { return _csv__WEBPACK_IMPORTED_MODULE_2__["CSVHeaderStyle"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "readCSV", function() { return _csv__WEBPACK_IMPORTED_MODULE_2__["readCSV"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSVReader", function() { return _csv__WEBPACK_IMPORTED_MODULE_2__["CSVReader"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toCSV", function() { return _csv__WEBPACK_IMPORTED_MODULE_2__["toCSV"]; });

/* harmony import */ var _logs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./logs */ "./packages/grafana-data/src/utils/logs.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLogLevel", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["getLogLevel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLogLevelFromKey", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["getLogLevelFromKey"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "addLogLevelToSeries", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["addLogLevelToSeries"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "calculateLogsLabelStats", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["calculateLogsLabelStats"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogsParsers", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["LogsParsers"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "calculateFieldStats", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["calculateFieldStats"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getParser", function() { return _logs__WEBPACK_IMPORTED_MODULE_3__["getParser"]; });

/* harmony import */ var _labels__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./labels */ "./packages/grafana-data/src/utils/labels.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parseLabels", function() { return _labels__WEBPACK_IMPORTED_MODULE_4__["parseLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findCommonLabels", function() { return _labels__WEBPACK_IMPORTED_MODULE_4__["findCommonLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "findUniqueLabels", function() { return _labels__WEBPACK_IMPORTED_MODULE_4__["findUniqueLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "formatLabels", function() { return _labels__WEBPACK_IMPORTED_MODULE_4__["formatLabels"]; });

/* empty/unused harmony star reexport *//* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./object */ "./packages/grafana-data/src/utils/object.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "objRemoveUndefined", function() { return _object__WEBPACK_IMPORTED_MODULE_5__["objRemoveUndefined"]; });

/* harmony import */ var _thresholds__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./thresholds */ "./packages/grafana-data/src/utils/thresholds.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getActiveThreshold", function() { return _thresholds__WEBPACK_IMPORTED_MODULE_6__["getActiveThreshold"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sortThresholds", function() { return _thresholds__WEBPACK_IMPORTED_MODULE_6__["sortThresholds"]; });

/* harmony import */ var _valueMappings__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./valueMappings */ "./packages/grafana-data/src/utils/valueMappings.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getMappedValue", function() { return _valueMappings__WEBPACK_IMPORTED_MODULE_7__["getMappedValue"]; });












/***/ }),

/***/ "./packages/grafana-data/src/utils/labels.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-data/src/utils/labels.ts ***!
  \***************************************************/
/*! exports provided: parseLabels, findCommonLabels, findUniqueLabels, formatLabels */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseLabels", function() { return parseLabels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findCommonLabels", function() { return findCommonLabels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findUniqueLabels", function() { return findUniqueLabels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatLabels", function() { return formatLabels; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

/**
 * Regexp to extract Prometheus-style labels
 */
var labelRegexp = /\b(\w+)(!?=~?)"([^"\n]*?)"/g;
/**
 * Returns a map of label keys to value from an input selector string.
 *
 * Example: `parseLabels('{job="foo", instance="bar"}) // {job: "foo", instance: "bar"}`
 */
function parseLabels(labels) {
    var labelsByKey = {};
    labels.replace(labelRegexp, function (_, key, operator, value) {
        labelsByKey[key] = value;
        return '';
    });
    return labelsByKey;
}
/**
 * Returns a map labels that are common to the given label sets.
 */
function findCommonLabels(labelsSets) {
    return labelsSets.reduce(function (acc, labels) {
        if (!labels) {
            throw new Error('Need parsed labels to find common labels.');
        }
        if (!acc) {
            // Initial set
            acc = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, labels);
        }
        else {
            // Remove incoming labels that are missing or not matching in value
            Object.keys(labels).forEach(function (key) {
                if (acc[key] === undefined || acc[key] !== labels[key]) {
                    delete acc[key];
                }
            });
            // Remove common labels that are missing from incoming label set
            Object.keys(acc).forEach(function (key) {
                if (labels[key] === undefined) {
                    delete acc[key];
                }
            });
        }
        return acc;
    }, undefined);
}
/**
 * Returns a map of labels that are in `labels`, but not in `commonLabels`.
 */
function findUniqueLabels(labels, commonLabels) {
    var uncommonLabels = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, labels);
    Object.keys(commonLabels).forEach(function (key) {
        delete uncommonLabels[key];
    });
    return uncommonLabels;
}
/**
 * Serializes the given labels to a string.
 */
function formatLabels(labels, defaultValue) {
    if (defaultValue === void 0) { defaultValue = ''; }
    if (!labels || Object.keys(labels).length === 0) {
        return defaultValue;
    }
    var labelKeys = Object.keys(labels).sort();
    var cleanSelector = labelKeys.map(function (key) { return key + "=\"" + labels[key] + "\""; }).join(', ');
    return ['{', cleanSelector, '}'].join('');
}


/***/ }),

/***/ "./packages/grafana-data/src/utils/logs.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-data/src/utils/logs.ts ***!
  \*************************************************/
/*! exports provided: getLogLevel, getLogLevelFromKey, addLogLevelToSeries, calculateLogsLabelStats, LogsParsers, calculateFieldStats, getParser */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLogLevel", function() { return getLogLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLogLevelFromKey", function() { return getLogLevelFromKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addLogLevelToSeries", function() { return addLogLevelToSeries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateLogsLabelStats", function() { return calculateLogsLabelStats; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogsParsers", function() { return LogsParsers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateFieldStats", function() { return calculateFieldStats; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getParser", function() { return getParser; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _types_logs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/logs */ "./packages/grafana-data/src/types/logs.ts");
/* harmony import */ var _types_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/index */ "./packages/grafana-data/src/types/index.ts");
/* harmony import */ var _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../vector/ArrayVector */ "./packages/grafana-data/src/vector/ArrayVector.ts");





var LOGFMT_REGEXP = /(?:^|\s)(\w+)=("[^"]*"|\S+)/;
/**
 * Returns the log level of a log line.
 * Parse the line for level words. If no level is found, it returns `LogLevel.unknown`.
 *
 * Example: `getLogLevel('WARN 1999-12-31 this is great') // LogLevel.warn`
 */
function getLogLevel(line) {
    var e_1, _a;
    if (!line) {
        return _types_logs__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].unknown;
    }
    try {
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](Object.keys(_types_logs__WEBPACK_IMPORTED_MODULE_2__["LogLevel"])), _c = _b.next(); !_c.done; _c = _b.next()) {
            var key = _c.value;
            var regexp = new RegExp("\\b" + key + "\\b", 'i');
            if (regexp.test(line)) {
                var level = _types_logs__WEBPACK_IMPORTED_MODULE_2__["LogLevel"][key];
                if (level) {
                    return level;
                }
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return _types_logs__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].unknown;
}
function getLogLevelFromKey(key) {
    var level = _types_logs__WEBPACK_IMPORTED_MODULE_2__["LogLevel"][key];
    if (level) {
        return level;
    }
    return _types_logs__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].unknown;
}
function addLogLevelToSeries(series, lineIndex) {
    var levels = new _vector_ArrayVector__WEBPACK_IMPORTED_MODULE_4__["ArrayVector"]();
    var lines = series.fields[lineIndex];
    for (var i = 0; i < lines.values.length; i++) {
        var line = lines.values.get(lineIndex);
        levels.buffer.push(getLogLevel(line));
    }
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { fields: tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](series.fields, [
            {
                name: 'LogLevel',
                type: _types_index__WEBPACK_IMPORTED_MODULE_3__["FieldType"].string,
                values: levels,
                config: {},
            },
        ]) });
}
function calculateLogsLabelStats(rows, label) {
    // Consider only rows that have the given label
    var rowsWithLabel = rows.filter(function (row) { return row.labels[label] !== undefined; });
    var rowCount = rowsWithLabel.length;
    // Get label value counts for eligible rows
    var countsByValue = Object(lodash__WEBPACK_IMPORTED_MODULE_1__["countBy"])(rowsWithLabel, function (row) { return row.labels[label]; });
    var sortedCounts = Object(lodash__WEBPACK_IMPORTED_MODULE_1__["chain"])(countsByValue)
        .map(function (count, value) { return ({ count: count, value: value, proportion: count / rowCount }); })
        .sortBy('count')
        .reverse()
        .value();
    return sortedCounts;
}
var LogsParsers = {
    JSON: {
        buildMatcher: function (label) { return new RegExp("(?:{|,)\\s*\"" + label + "\"\\s*:\\s*\"?([\\d\\.]+|[^\"]*)\"?"); },
        getFields: function (line) {
            var fields = [];
            try {
                var parsed = JSON.parse(line);
                Object(lodash__WEBPACK_IMPORTED_MODULE_1__["map"])(parsed, function (value, key) {
                    var fieldMatcher = new RegExp("\"" + key + "\"\\s*:\\s*\"?" + Object(lodash__WEBPACK_IMPORTED_MODULE_1__["escapeRegExp"])(JSON.stringify(value)) + "\"?");
                    var match = line.match(fieldMatcher);
                    if (match) {
                        fields.push(match[0]);
                    }
                });
            }
            catch (_a) { }
            return fields;
        },
        getLabelFromField: function (field) { return (field.match(/^"(\w+)"\s*:/) || [])[1]; },
        getValueFromField: function (field) { return (field.match(/:\s*(.*)$/) || [])[1]; },
        test: function (line) {
            try {
                return JSON.parse(line);
            }
            catch (error) { }
        },
    },
    logfmt: {
        buildMatcher: function (label) { return new RegExp("(?:^|\\s)" + label + "=(\"[^\"]*\"|\\S+)"); },
        getFields: function (line) {
            var fields = [];
            line.replace(new RegExp(LOGFMT_REGEXP, 'g'), function (substring) {
                fields.push(substring.trim());
                return '';
            });
            return fields;
        },
        getLabelFromField: function (field) { return (field.match(LOGFMT_REGEXP) || [])[1]; },
        getValueFromField: function (field) { return (field.match(LOGFMT_REGEXP) || [])[2]; },
        test: function (line) { return LOGFMT_REGEXP.test(line); },
    },
};
function calculateFieldStats(rows, extractor) {
    // Consider only rows that satisfy the matcher
    var rowsWithField = rows.filter(function (row) { return extractor.test(row.entry); });
    var rowCount = rowsWithField.length;
    // Get field value counts for eligible rows
    var countsByValue = Object(lodash__WEBPACK_IMPORTED_MODULE_1__["countBy"])(rowsWithField, function (r) {
        var row = r;
        var match = row.entry.match(extractor);
        return match ? match[1] : null;
    });
    var sortedCounts = Object(lodash__WEBPACK_IMPORTED_MODULE_1__["chain"])(countsByValue)
        .map(function (count, value) { return ({ count: count, value: value, proportion: count / rowCount }); })
        .sortBy('count')
        .reverse()
        .value();
    return sortedCounts;
}
function getParser(line) {
    var parser;
    try {
        if (LogsParsers.JSON.test(line)) {
            parser = LogsParsers.JSON;
        }
    }
    catch (error) { }
    if (!parser && LogsParsers.logfmt.test(line)) {
        parser = LogsParsers.logfmt;
    }
    return parser;
}


/***/ }),

/***/ "./packages/grafana-data/src/utils/object.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-data/src/utils/object.ts ***!
  \***************************************************/
/*! exports provided: objRemoveUndefined */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "objRemoveUndefined", function() { return objRemoveUndefined; });
var objRemoveUndefined = function (obj) {
    return Object.keys(obj).reduce(function (acc, key) {
        if (obj[key] !== undefined) {
            acc[key] = obj[key];
        }
        return acc;
    }, {});
};


/***/ }),

/***/ "./packages/grafana-data/src/utils/thresholds.ts":
/*!*******************************************************!*\
  !*** ./packages/grafana-data/src/utils/thresholds.ts ***!
  \*******************************************************/
/*! exports provided: getActiveThreshold, sortThresholds */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getActiveThreshold", function() { return getActiveThreshold; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortThresholds", function() { return sortThresholds; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

function getActiveThreshold(value, thresholds) {
    var e_1, _a;
    var active = thresholds[0];
    try {
        for (var thresholds_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](thresholds), thresholds_1_1 = thresholds_1.next(); !thresholds_1_1.done; thresholds_1_1 = thresholds_1.next()) {
            var threshold = thresholds_1_1.value;
            if (value >= threshold.value) {
                active = threshold;
            }
            else {
                break;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (thresholds_1_1 && !thresholds_1_1.done && (_a = thresholds_1.return)) _a.call(thresholds_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return active;
}
/**
 * Sorts the thresholds
 */
function sortThresholds(thresholds) {
    return thresholds.sort(function (t1, t2) {
        return t1.value - t2.value;
    });
}


/***/ }),

/***/ "./packages/grafana-data/src/utils/valueMappings.ts":
/*!**********************************************************!*\
  !*** ./packages/grafana-data/src/utils/valueMappings.ts ***!
  \**********************************************************/
/*! exports provided: getMappedValue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMappedValue", function() { return getMappedValue; });
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types */ "./packages/grafana-data/src/types/index.ts");

var addValueToTextMappingText = function (allValueMappings, valueToTextMapping, value) {
    if (valueToTextMapping.value === undefined) {
        return allValueMappings;
    }
    if (value === null && valueToTextMapping.value && valueToTextMapping.value.toLowerCase() === 'null') {
        return allValueMappings.concat(valueToTextMapping);
    }
    var valueAsNumber = parseFloat(value);
    var valueToTextMappingAsNumber = parseFloat(valueToTextMapping.value);
    if (isNaN(valueAsNumber) || isNaN(valueToTextMappingAsNumber)) {
        return allValueMappings;
    }
    if (valueAsNumber !== valueToTextMappingAsNumber) {
        return allValueMappings;
    }
    return allValueMappings.concat(valueToTextMapping);
};
var addRangeToTextMappingText = function (allValueMappings, rangeToTextMapping, value) {
    if (rangeToTextMapping.from === undefined || rangeToTextMapping.to === undefined || value === undefined) {
        return allValueMappings;
    }
    if (value === null &&
        rangeToTextMapping.from &&
        rangeToTextMapping.to &&
        rangeToTextMapping.from.toLowerCase() === 'null' &&
        rangeToTextMapping.to.toLowerCase() === 'null') {
        return allValueMappings.concat(rangeToTextMapping);
    }
    var valueAsNumber = parseFloat(value);
    var fromAsNumber = parseFloat(rangeToTextMapping.from);
    var toAsNumber = parseFloat(rangeToTextMapping.to);
    if (isNaN(valueAsNumber) || isNaN(fromAsNumber) || isNaN(toAsNumber)) {
        return allValueMappings;
    }
    if (valueAsNumber >= fromAsNumber && valueAsNumber <= toAsNumber) {
        return allValueMappings.concat(rangeToTextMapping);
    }
    return allValueMappings;
};
var getAllFormattedValueMappings = function (valueMappings, value) {
    var allFormattedValueMappings = valueMappings.reduce(function (allValueMappings, valueMapping) {
        if (valueMapping.type === _types__WEBPACK_IMPORTED_MODULE_0__["MappingType"].ValueToText) {
            allValueMappings = addValueToTextMappingText(allValueMappings, valueMapping, value);
        }
        else if (valueMapping.type === _types__WEBPACK_IMPORTED_MODULE_0__["MappingType"].RangeToText) {
            allValueMappings = addRangeToTextMappingText(allValueMappings, valueMapping, value);
        }
        return allValueMappings;
    }, []);
    allFormattedValueMappings.sort(function (t1, t2) {
        return t1.id - t2.id;
    });
    return allFormattedValueMappings;
};
var getMappedValue = function (valueMappings, value) {
    return getAllFormattedValueMappings(valueMappings, value)[0];
};


/***/ }),

/***/ "./packages/grafana-data/src/vector/AppendedVectors.ts":
/*!*************************************************************!*\
  !*** ./packages/grafana-data/src/vector/AppendedVectors.ts ***!
  \*************************************************************/
/*! exports provided: AppendedVectors */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppendedVectors", function() { return AppendedVectors; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _vectorToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vectorToArray */ "./packages/grafana-data/src/vector/vectorToArray.ts");


/**
 * This may be more trouble than it is worth.  This trades some computation time for
 * RAM -- rather than allocate a new array the size of all previous arrays, this just
 * points the correct index to their original array values
 */
var AppendedVectors = /** @class */ (function () {
    function AppendedVectors(startAt) {
        if (startAt === void 0) { startAt = 0; }
        this.length = 0;
        this.source = new Array();
        this.length = startAt;
    }
    /**
     * Make the vector look like it is this long
     */
    AppendedVectors.prototype.setLength = function (length) {
        var e_1, _a;
        if (length > this.length) {
            // make the vector longer (filling with undefined)
            this.length = length;
        }
        else if (length < this.length) {
            // make the array shorter
            var sources = new Array();
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.source), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var src = _c.value;
                    sources.push(src);
                    if (src.end > length) {
                        src.end = length;
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            this.source = sources;
            this.length = length;
        }
    };
    AppendedVectors.prototype.append = function (v) {
        var info = {
            start: this.length,
            end: this.length + v.length,
            values: v,
        };
        this.length = info.end;
        this.source.push(info);
        return info;
    };
    AppendedVectors.prototype.get = function (index) {
        for (var i = 0; i < this.source.length; i++) {
            var src = this.source[i];
            if (index >= src.start && index < src.end) {
                return src.values.get(index - src.start);
            }
        }
        return undefined;
    };
    AppendedVectors.prototype.toArray = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_1__["vectorToArray"])(this);
    };
    AppendedVectors.prototype.toJSON = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_1__["vectorToArray"])(this);
    };
    return AppendedVectors;
}());



/***/ }),

/***/ "./packages/grafana-data/src/vector/ArrayVector.ts":
/*!*********************************************************!*\
  !*** ./packages/grafana-data/src/vector/ArrayVector.ts ***!
  \*********************************************************/
/*! exports provided: ArrayVector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayVector", function() { return ArrayVector; });
var ArrayVector = /** @class */ (function () {
    function ArrayVector(buffer) {
        this.buffer = buffer ? buffer : [];
    }
    Object.defineProperty(ArrayVector.prototype, "length", {
        get: function () {
            return this.buffer.length;
        },
        enumerable: true,
        configurable: true
    });
    ArrayVector.prototype.add = function (value) {
        this.buffer.push(value);
    };
    ArrayVector.prototype.get = function (index) {
        return this.buffer[index];
    };
    ArrayVector.prototype.set = function (index, value) {
        this.buffer[index] = value;
    };
    ArrayVector.prototype.reverse = function () {
        this.buffer.reverse();
    };
    ArrayVector.prototype.toArray = function () {
        return this.buffer;
    };
    ArrayVector.prototype.toJSON = function () {
        return this.buffer;
    };
    return ArrayVector;
}());



/***/ }),

/***/ "./packages/grafana-data/src/vector/CircularVector.ts":
/*!************************************************************!*\
  !*** ./packages/grafana-data/src/vector/CircularVector.ts ***!
  \************************************************************/
/*! exports provided: CircularVector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircularVector", function() { return CircularVector; });
/* harmony import */ var _vectorToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vectorToArray */ "./packages/grafana-data/src/vector/vectorToArray.ts");

/**
 * Circular vector uses a single buffer to capture a stream of values
 * overwriting the oldest value on add.
 *
 * This supports addting to the 'head' or 'tail' and will grow the buffer
 * to match a configured capacity.
 */
var CircularVector = /** @class */ (function () {
    function CircularVector(options) {
        this.buffer = options.buffer || [];
        this.capacity = this.buffer.length;
        this.tail = 'head' !== options.append;
        this.index = 0;
        this.add = this.getAddFunction();
        if (options.capacity) {
            this.setCapacity(options.capacity);
        }
    }
    /**
     * This gets the appropriate add function depending on the buffer state:
     *  * head vs tail
     *  * growing buffer vs overwriting values
     */
    CircularVector.prototype.getAddFunction = function () {
        var _this = this;
        // When we are not at capacity, it should actually modify the buffer
        if (this.capacity > this.buffer.length) {
            if (this.tail) {
                return function (value) {
                    _this.buffer.push(value);
                    if (_this.buffer.length >= _this.capacity) {
                        _this.add = _this.getAddFunction();
                    }
                };
            }
            else {
                return function (value) {
                    _this.buffer.unshift(value);
                    if (_this.buffer.length >= _this.capacity) {
                        _this.add = _this.getAddFunction();
                    }
                };
            }
        }
        if (this.tail) {
            return function (value) {
                _this.buffer[_this.index] = value;
                _this.index = (_this.index + 1) % _this.buffer.length;
            };
        }
        // Append values to the head
        return function (value) {
            var idx = _this.index - 1;
            if (idx < 0) {
                idx = _this.buffer.length - 1;
            }
            _this.buffer[idx] = value;
            _this.index = idx;
        };
    };
    CircularVector.prototype.setCapacity = function (v) {
        if (this.capacity === v) {
            return;
        }
        // Make a copy so it is in order and new additions can be at the head or tail
        var copy = this.toArray();
        if (v > this.length) {
            this.buffer = copy;
        }
        else if (v < this.capacity) {
            // Shrink the buffer
            var delta = this.length - v;
            if (this.tail) {
                this.buffer = copy.slice(delta, copy.length); // Keep last items
            }
            else {
                this.buffer = copy.slice(0, copy.length - delta); // Keep first items
            }
        }
        this.capacity = v;
        this.index = 0;
        this.add = this.getAddFunction();
    };
    CircularVector.prototype.setAppendMode = function (mode) {
        var tail = 'head' !== mode;
        if (tail !== this.tail) {
            this.buffer = this.toArray().reverse();
            this.index = 0;
            this.tail = tail;
            this.add = this.getAddFunction();
        }
    };
    CircularVector.prototype.reverse = function () {
        this.buffer.reverse();
    };
    CircularVector.prototype.get = function (index) {
        return this.buffer[(index + this.index) % this.buffer.length];
    };
    CircularVector.prototype.set = function (index, value) {
        this.buffer[(index + this.index) % this.buffer.length] = value;
    };
    Object.defineProperty(CircularVector.prototype, "length", {
        get: function () {
            return this.buffer.length;
        },
        enumerable: true,
        configurable: true
    });
    CircularVector.prototype.toArray = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_0__["vectorToArray"])(this);
    };
    CircularVector.prototype.toJSON = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_0__["vectorToArray"])(this);
    };
    return CircularVector;
}());



/***/ }),

/***/ "./packages/grafana-data/src/vector/ConstantVector.ts":
/*!************************************************************!*\
  !*** ./packages/grafana-data/src/vector/ConstantVector.ts ***!
  \************************************************************/
/*! exports provided: ConstantVector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConstantVector", function() { return ConstantVector; });
var ConstantVector = /** @class */ (function () {
    function ConstantVector(value, len) {
        this.value = value;
        this.len = len;
    }
    Object.defineProperty(ConstantVector.prototype, "length", {
        get: function () {
            return this.len;
        },
        enumerable: true,
        configurable: true
    });
    ConstantVector.prototype.get = function (index) {
        return this.value;
    };
    ConstantVector.prototype.toArray = function () {
        var arr = new Array(this.length);
        return arr.fill(this.value);
    };
    ConstantVector.prototype.toJSON = function () {
        return this.toArray();
    };
    return ConstantVector;
}());



/***/ }),

/***/ "./packages/grafana-data/src/vector/ScaledVector.ts":
/*!**********************************************************!*\
  !*** ./packages/grafana-data/src/vector/ScaledVector.ts ***!
  \**********************************************************/
/*! exports provided: ScaledVector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaledVector", function() { return ScaledVector; });
/* harmony import */ var _vectorToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vectorToArray */ "./packages/grafana-data/src/vector/vectorToArray.ts");

var ScaledVector = /** @class */ (function () {
    function ScaledVector(source, scale) {
        this.source = source;
        this.scale = scale;
    }
    Object.defineProperty(ScaledVector.prototype, "length", {
        get: function () {
            return this.source.length;
        },
        enumerable: true,
        configurable: true
    });
    ScaledVector.prototype.get = function (index) {
        return this.source.get(index) * this.scale;
    };
    ScaledVector.prototype.toArray = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_0__["vectorToArray"])(this);
    };
    ScaledVector.prototype.toJSON = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_0__["vectorToArray"])(this);
    };
    return ScaledVector;
}());



/***/ }),

/***/ "./packages/grafana-data/src/vector/SortedVector.ts":
/*!**********************************************************!*\
  !*** ./packages/grafana-data/src/vector/SortedVector.ts ***!
  \**********************************************************/
/*! exports provided: SortedVector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SortedVector", function() { return SortedVector; });
/* harmony import */ var _vectorToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vectorToArray */ "./packages/grafana-data/src/vector/vectorToArray.ts");

/**
 * Values are returned in the order defined by the input parameter
 */
var SortedVector = /** @class */ (function () {
    function SortedVector(source, order) {
        this.source = source;
        this.order = order;
    }
    Object.defineProperty(SortedVector.prototype, "length", {
        get: function () {
            return this.source.length;
        },
        enumerable: true,
        configurable: true
    });
    SortedVector.prototype.get = function (index) {
        return this.source.get(this.order[index]);
    };
    SortedVector.prototype.toArray = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_0__["vectorToArray"])(this);
    };
    SortedVector.prototype.toJSON = function () {
        return Object(_vectorToArray__WEBPACK_IMPORTED_MODULE_0__["vectorToArray"])(this);
    };
    return SortedVector;
}());



/***/ }),

/***/ "./packages/grafana-data/src/vector/index.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-data/src/vector/index.ts ***!
  \***************************************************/
/*! exports provided: AppendedVectors, ArrayVector, CircularVector, ConstantVector, ScaledVector, SortedVector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AppendedVectors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AppendedVectors */ "./packages/grafana-data/src/vector/AppendedVectors.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AppendedVectors", function() { return _AppendedVectors__WEBPACK_IMPORTED_MODULE_0__["AppendedVectors"]; });

/* harmony import */ var _ArrayVector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ArrayVector */ "./packages/grafana-data/src/vector/ArrayVector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArrayVector", function() { return _ArrayVector__WEBPACK_IMPORTED_MODULE_1__["ArrayVector"]; });

/* harmony import */ var _CircularVector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CircularVector */ "./packages/grafana-data/src/vector/CircularVector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircularVector", function() { return _CircularVector__WEBPACK_IMPORTED_MODULE_2__["CircularVector"]; });

/* harmony import */ var _ConstantVector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ConstantVector */ "./packages/grafana-data/src/vector/ConstantVector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConstantVector", function() { return _ConstantVector__WEBPACK_IMPORTED_MODULE_3__["ConstantVector"]; });

/* harmony import */ var _ScaledVector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ScaledVector */ "./packages/grafana-data/src/vector/ScaledVector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaledVector", function() { return _ScaledVector__WEBPACK_IMPORTED_MODULE_4__["ScaledVector"]; });

/* harmony import */ var _SortedVector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SortedVector */ "./packages/grafana-data/src/vector/SortedVector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SortedVector", function() { return _SortedVector__WEBPACK_IMPORTED_MODULE_5__["SortedVector"]; });









/***/ }),

/***/ "./packages/grafana-data/src/vector/vectorToArray.ts":
/*!***********************************************************!*\
  !*** ./packages/grafana-data/src/vector/vectorToArray.ts ***!
  \***********************************************************/
/*! exports provided: vectorToArray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "vectorToArray", function() { return vectorToArray; });
function vectorToArray(v) {
    var arr = [];
    for (var i = 0; i < v.length; i++) {
        arr[i] = v.get(i);
    }
    return arr;
}


/***/ }),

/***/ "./packages/grafana-runtime/src/config.ts":
/*!************************************************!*\
  !*** ./packages/grafana-runtime/src/config.ts ***!
  \************************************************/
/*! exports provided: GrafanaBootConfig, config */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GrafanaBootConfig", function() { return GrafanaBootConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "config", function() { return config; });
/* harmony import */ var lodash_extend__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash/extend */ "./node_modules/lodash/extend.js");
/* harmony import */ var lodash_extend__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash_extend__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


var GrafanaBootConfig = /** @class */ (function () {
    function GrafanaBootConfig(options) {
        this.datasources = {};
        this.panels = {};
        this.appSubUrl = '';
        this.windowTitlePrefix = '';
        this.buildInfo = {};
        this.newPanelTitle = '';
        this.externalUserMngLinkUrl = '';
        this.externalUserMngLinkName = '';
        this.externalUserMngInfo = '';
        this.allowOrgCreate = false;
        this.disableLoginForm = false;
        this.defaultDatasource = '';
        this.alertingEnabled = false;
        this.alertingErrorOrTimeout = '';
        this.alertingNoDataOrNullValues = '';
        this.authProxyEnabled = false;
        this.exploreEnabled = false;
        this.ldapEnabled = false;
        this.samlEnabled = false;
        this.disableUserSignUp = false;
        this.viewersCanEdit = false;
        this.editorsCanAdmin = false;
        this.disableSanitizeHtml = false;
        this.pluginsToPreload = [];
        this.featureToggles = {
            transformations: false,
        };
        this.theme = options.bootData.user.lightTheme ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getTheme"])(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["GrafanaThemeType"].Light) : Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getTheme"])(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["GrafanaThemeType"].Dark);
        var defaults = {
            datasources: {},
            windowTitlePrefix: 'Grafana - ',
            panels: {},
            newPanelTitle: 'Panel Title',
            playlist_timespan: '1m',
            unsaved_changes_warning: true,
            appSubUrl: '',
            buildInfo: {
                version: 'v1.0',
                commit: '1',
                env: 'production',
                isEnterprise: false,
            },
            viewersCanEdit: false,
            editorsCanAdmin: false,
            disableSanitizeHtml: false,
        };
        lodash_extend__WEBPACK_IMPORTED_MODULE_0___default()(this, defaults, options);
    }
    return GrafanaBootConfig;
}());

var bootData = window.grafanaBootData || {
    settings: {},
    user: {},
};
var options = bootData.settings;
options.bootData = bootData;
var config = new GrafanaBootConfig(options);


/***/ }),

/***/ "./packages/grafana-runtime/src/index.ts":
/*!***********************************************!*\
  !*** ./packages/grafana-runtime/src/index.ts ***!
  \***********************************************/
/*! exports provided: GrafanaBootConfig, config, loadPluginCss, SystemJS, setBackendSrv, getBackendSrv, setAngularLoader, getAngularLoader, setDataSourceSrv, getDataSourceSrv, setLocationSrv, getLocationSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _services__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./services */ "./packages/grafana-runtime/src/services/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setBackendSrv", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["setBackendSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBackendSrv", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["getBackendSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setAngularLoader", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["setAngularLoader"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getAngularLoader", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["getAngularLoader"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setDataSourceSrv", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["setDataSourceSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDataSourceSrv", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["getDataSourceSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setLocationSrv", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["setLocationSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLocationSrv", function() { return _services__WEBPACK_IMPORTED_MODULE_0__["getLocationSrv"]; });

/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./config */ "./packages/grafana-runtime/src/config.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GrafanaBootConfig", function() { return _config__WEBPACK_IMPORTED_MODULE_1__["GrafanaBootConfig"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "config", function() { return _config__WEBPACK_IMPORTED_MODULE_1__["config"]; });

/* harmony import */ var _utils_plugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/plugin */ "./packages/grafana-runtime/src/utils/plugin.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "loadPluginCss", function() { return _utils_plugin__WEBPACK_IMPORTED_MODULE_2__["loadPluginCss"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SystemJS", function() { return _utils_plugin__WEBPACK_IMPORTED_MODULE_2__["SystemJS"]; });






/***/ }),

/***/ "./packages/grafana-runtime/src/services/AngularLoader.ts":
/*!****************************************************************!*\
  !*** ./packages/grafana-runtime/src/services/AngularLoader.ts ***!
  \****************************************************************/
/*! exports provided: setAngularLoader, getAngularLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setAngularLoader", function() { return setAngularLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAngularLoader", function() { return getAngularLoader; });
var instance;
function setAngularLoader(v) {
    instance = v;
}
function getAngularLoader() {
    return instance;
}


/***/ }),

/***/ "./packages/grafana-runtime/src/services/LocationSrv.ts":
/*!**************************************************************!*\
  !*** ./packages/grafana-runtime/src/services/LocationSrv.ts ***!
  \**************************************************************/
/*! exports provided: setLocationSrv, getLocationSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setLocationSrv", function() { return setLocationSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocationSrv", function() { return getLocationSrv; });
var singletonInstance;
function setLocationSrv(instance) {
    singletonInstance = instance;
}
function getLocationSrv() {
    return singletonInstance;
}


/***/ }),

/***/ "./packages/grafana-runtime/src/services/backendSrv.ts":
/*!*************************************************************!*\
  !*** ./packages/grafana-runtime/src/services/backendSrv.ts ***!
  \*************************************************************/
/*! exports provided: setBackendSrv, getBackendSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBackendSrv", function() { return setBackendSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBackendSrv", function() { return getBackendSrv; });
var singletonInstance;
function setBackendSrv(instance) {
    singletonInstance = instance;
}
function getBackendSrv() {
    return singletonInstance;
}


/***/ }),

/***/ "./packages/grafana-runtime/src/services/dataSourceSrv.ts":
/*!****************************************************************!*\
  !*** ./packages/grafana-runtime/src/services/dataSourceSrv.ts ***!
  \****************************************************************/
/*! exports provided: setDataSourceSrv, getDataSourceSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDataSourceSrv", function() { return setDataSourceSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataSourceSrv", function() { return getDataSourceSrv; });
var singletonInstance;
function setDataSourceSrv(instance) {
    singletonInstance = instance;
}
function getDataSourceSrv() {
    return singletonInstance;
}


/***/ }),

/***/ "./packages/grafana-runtime/src/services/index.ts":
/*!********************************************************!*\
  !*** ./packages/grafana-runtime/src/services/index.ts ***!
  \********************************************************/
/*! exports provided: setBackendSrv, getBackendSrv, setAngularLoader, getAngularLoader, setDataSourceSrv, getDataSourceSrv, setLocationSrv, getLocationSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _backendSrv__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backendSrv */ "./packages/grafana-runtime/src/services/backendSrv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setBackendSrv", function() { return _backendSrv__WEBPACK_IMPORTED_MODULE_0__["setBackendSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getBackendSrv", function() { return _backendSrv__WEBPACK_IMPORTED_MODULE_0__["getBackendSrv"]; });

/* harmony import */ var _AngularLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AngularLoader */ "./packages/grafana-runtime/src/services/AngularLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setAngularLoader", function() { return _AngularLoader__WEBPACK_IMPORTED_MODULE_1__["setAngularLoader"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getAngularLoader", function() { return _AngularLoader__WEBPACK_IMPORTED_MODULE_1__["getAngularLoader"]; });

/* harmony import */ var _dataSourceSrv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dataSourceSrv */ "./packages/grafana-runtime/src/services/dataSourceSrv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setDataSourceSrv", function() { return _dataSourceSrv__WEBPACK_IMPORTED_MODULE_2__["setDataSourceSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDataSourceSrv", function() { return _dataSourceSrv__WEBPACK_IMPORTED_MODULE_2__["getDataSourceSrv"]; });

/* harmony import */ var _LocationSrv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LocationSrv */ "./packages/grafana-runtime/src/services/LocationSrv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "setLocationSrv", function() { return _LocationSrv__WEBPACK_IMPORTED_MODULE_3__["setLocationSrv"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLocationSrv", function() { return _LocationSrv__WEBPACK_IMPORTED_MODULE_3__["getLocationSrv"]; });







/***/ }),

/***/ "./packages/grafana-runtime/src/utils/plugin.ts":
/*!******************************************************!*\
  !*** ./packages/grafana-runtime/src/utils/plugin.ts ***!
  \******************************************************/
/*! exports provided: SystemJS, loadPluginCss */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SystemJS", function() { return SystemJS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPluginCss", function() { return loadPluginCss; });
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config */ "./packages/grafana-runtime/src/config.ts");
/* harmony import */ var systemjs_dist_system_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! systemjs/dist/system.js */ "./node_modules/systemjs/dist/system.js");
/* harmony import */ var systemjs_dist_system_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(systemjs_dist_system_js__WEBPACK_IMPORTED_MODULE_1__);

// @ts-ignore

var SystemJS = systemjs_dist_system_js__WEBPACK_IMPORTED_MODULE_1___default.a;
function loadPluginCss(options) {
    var theme = _config__WEBPACK_IMPORTED_MODULE_0__["config"].bootData.user.lightTheme ? options.light : options.dark;
    return SystemJS.import(theme + "!css");
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/Alert/Alert.tsx":
/*!************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Alert/Alert.tsx ***!
  \************************************************************/
/*! exports provided: Alert */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Alert", function() { return Alert; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var Alert = function (props) {
    var title = props.title, button = props.button, children = props.children;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-container" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-error alert" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-icon" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-exclamation-triangle" })),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-body" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-title" }, title),
                children && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-text" }, children)),
            button && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-button" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { className: "btn btn-outline-danger", onClick: button.onClick }, button.text))))));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/AlphaNotice/AlphaNotice.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/AlphaNotice/AlphaNotice.tsx ***!
  \************************************************************************/
/*! exports provided: AlphaNotice */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlphaNotice", function() { return AlphaNotice; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../index */ "./packages/grafana-ui/src/index.ts");




var AlphaNotice = function (_a) {
    var state = _a.state, text = _a.text, className = _a.className;
    var tooltipContent = text || 'This feature is a work in progress and updates may include breaking changes';
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    var styles = Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(className, Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      background: linear-gradient(to bottom, ", ", ", ");\n      color: ", ";\n      white-space: nowrap;\n      border-radius: 3px;\n      text-shadow: none;\n      font-size: 13px;\n      padding: 4px 8px;\n      cursor: help;\n      display: inline-block;\n    "], ["\n      background: linear-gradient(to bottom, ", ", ", ");\n      color: ", ";\n      white-space: nowrap;\n      border-radius: 3px;\n      text-shadow: none;\n      font-size: 13px;\n      padding: 4px 8px;\n      cursor: help;\n      display: inline-block;\n    "])), theme.colors.blueBase, theme.colors.blueShade, theme.colors.gray7));
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles, title: tooltipContent },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-warning" }),
        " ",
        state));
};
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/BarGauge/BarGauge.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/BarGauge/BarGauge.tsx ***!
  \******************************************************************/
/*! exports provided: BarGauge, getTitleStyles, getValuePercent, getBasicAndGradientStyles, getBarGradient, getValueColor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BarGauge", function() { return BarGauge; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTitleStyles", function() { return getTitleStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValuePercent", function() { return getValuePercent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBasicAndGradientStyles", function() { return getBasicAndGradientStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBarGradient", function() { return getBarGradient; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValueColor", function() { return getValueColor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils */ "./packages/grafana-ui/src/utils/index.ts");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../types */ "./packages/grafana-ui/src/types/index.ts");

// Library



// Utils

// Types

var MIN_VALUE_HEIGHT = 18;
var MAX_VALUE_HEIGHT = 50;
var MIN_VALUE_WIDTH = 50;
var MAX_VALUE_WIDTH = 150;
var TITLE_LINE_HEIGHT = 1.5;
var VALUE_LINE_HEIGHT = 1;
var BarGauge = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BarGauge, _super);
    function BarGauge() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BarGauge.prototype.render = function () {
        var _a = this.props, onClick = _a.onClick, className = _a.className;
        var title = this.props.value.title;
        var styles = getTitleStyles(this.props);
        if (!title) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: styles.wrapper, onClick: onClick, className: className }, this.renderBarAndValue()));
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: styles.wrapper, onClick: onClick, className: className },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: styles.title }, title),
            this.renderBarAndValue()));
    };
    BarGauge.prototype.renderBarAndValue = function () {
        switch (this.props.displayMode) {
            case 'lcd':
                return this.renderRetroBars();
            case 'basic':
            case 'gradient':
            default:
                return this.renderBasicAndGradientBars();
        }
    };
    BarGauge.prototype.renderBasicAndGradientBars = function () {
        var value = this.props.value;
        var styles = getBasicAndGradientStyles(this.props);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: styles.wrapper },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "bar-gauge__value", style: styles.value }, value.text),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: styles.bar })));
    };
    BarGauge.prototype.getCellColor = function (positionValue) {
        var _a = this.props, thresholds = _a.thresholds, theme = _a.theme, value = _a.value;
        if (positionValue === null) {
            return {
                background: 'gray',
                border: 'gray',
            };
        }
        var activeThreshold = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["getActiveThreshold"])(positionValue, thresholds);
        if (activeThreshold !== null) {
            var color = Object(_utils__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])(activeThreshold.color, theme.type);
            // if we are past real value the cell is not "on"
            if (value === null || (positionValue !== null && positionValue > value.numeric)) {
                return {
                    background: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(color)
                        .setAlpha(0.18)
                        .toRgbString(),
                    border: 'transparent',
                    isLit: false,
                };
            }
            else {
                return {
                    background: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(color)
                        .setAlpha(0.95)
                        .toRgbString(),
                    backgroundShade: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(color)
                        .setAlpha(0.55)
                        .toRgbString(),
                    border: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(color)
                        .setAlpha(0.9)
                        .toRgbString(),
                    isLit: true,
                };
            }
        }
        return {
            background: 'gray',
            border: 'gray',
        };
    };
    BarGauge.prototype.renderRetroBars = function () {
        var _a = this.props, maxValue = _a.maxValue, minValue = _a.minValue, value = _a.value, itemSpacing = _a.itemSpacing;
        var _b = calculateBarAndValueDimensions(this.props), valueHeight = _b.valueHeight, valueWidth = _b.valueWidth, maxBarHeight = _b.maxBarHeight, maxBarWidth = _b.maxBarWidth, wrapperWidth = _b.wrapperWidth, wrapperHeight = _b.wrapperHeight;
        var isVert = isVertical(this.props);
        var valueRange = maxValue - minValue;
        var maxSize = isVert ? maxBarHeight : maxBarWidth;
        var cellSpacing = itemSpacing;
        var cellWidth = 12;
        var cellCount = Math.floor(maxSize / cellWidth);
        var cellSize = Math.floor((maxSize - cellSpacing * cellCount) / cellCount);
        var valueColor = getValueColor(this.props);
        var valueStyles = getValueStyles(value.text, valueColor, valueWidth, valueHeight);
        var containerStyles = {
            width: wrapperWidth + "px",
            height: wrapperHeight + "px",
            display: 'flex',
        };
        if (isVert) {
            containerStyles.flexDirection = 'column-reverse';
            containerStyles.alignItems = 'center';
            valueStyles.justifyContent = 'center';
        }
        else {
            containerStyles.flexDirection = 'row';
            containerStyles.alignItems = 'center';
            valueStyles.justifyContent = 'flex-end';
        }
        var cells = [];
        for (var i = 0; i < cellCount; i++) {
            var currentValue = minValue + (valueRange / cellCount) * i;
            var cellColor = this.getCellColor(currentValue);
            var cellStyles = {
                borderRadius: '2px',
            };
            if (cellColor.isLit) {
                cellStyles.backgroundImage = "radial-gradient(" + cellColor.background + " 10%, " + cellColor.backgroundShade + ")";
            }
            else {
                cellStyles.backgroundColor = cellColor.background;
            }
            if (isVert) {
                cellStyles.height = cellSize + "px";
                cellStyles.width = maxBarWidth + "px";
                cellStyles.marginTop = cellSpacing + "px";
            }
            else {
                cellStyles.width = cellSize + "px";
                cellStyles.height = maxBarHeight + "px";
                cellStyles.marginRight = cellSpacing + "px";
            }
            cells.push(react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { key: i.toString(), style: cellStyles }));
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: containerStyles },
            cells,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "bar-gauge__value", style: valueStyles }, value.text)));
    };
    BarGauge.defaultProps = {
        maxValue: 100,
        minValue: 0,
        value: {
            text: '100',
            numeric: 100,
        },
        displayMode: 'lcd',
        orientation: _types__WEBPACK_IMPORTED_MODULE_5__["VizOrientation"].Horizontal,
        thresholds: [],
        itemSpacing: 10,
    };
    return BarGauge;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

function isVertical(props) {
    return props.orientation === _types__WEBPACK_IMPORTED_MODULE_5__["VizOrientation"].Vertical;
}
function calculateTitleDimensions(props) {
    var title = props.value.title;
    var height = props.height, width = props.width;
    if (!title) {
        return { fontSize: 0, width: 0, height: 0, placement: 'above' };
    }
    if (isVertical(props)) {
        return {
            fontSize: 14,
            width: width,
            height: 14 * TITLE_LINE_HEIGHT,
            placement: 'below',
        };
    }
    // if height above 40 put text to above bar
    if (height > 40) {
        var maxTitleHeightRatio_1 = 0.35;
        var titleHeight_1 = Math.max(Math.min(height * maxTitleHeightRatio_1, MAX_VALUE_HEIGHT), 17);
        return {
            fontSize: titleHeight_1 / TITLE_LINE_HEIGHT,
            width: 0,
            height: titleHeight_1,
            placement: 'above',
        };
    }
    // title to left of bar scenario
    var maxTitleHeightRatio = 0.6;
    var maxTitleWidthRatio = 0.2;
    var titleHeight = Math.max(height * maxTitleHeightRatio, MIN_VALUE_HEIGHT);
    return {
        fontSize: titleHeight / TITLE_LINE_HEIGHT,
        height: 0,
        width: Math.min(Math.max(width * maxTitleWidthRatio, 50), 200),
        placement: 'left',
    };
}
function getTitleStyles(props) {
    var wrapperStyles = {
        display: 'flex',
        overflow: 'hidden',
    };
    var titleDim = calculateTitleDimensions(props);
    var titleStyles = {
        fontSize: titleDim.fontSize + "px",
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        width: '100%',
        alignItems: 'center',
        alignSelf: 'center',
    };
    if (isVertical(props)) {
        wrapperStyles.flexDirection = 'column-reverse';
        titleStyles.textAlign = 'center';
    }
    else {
        if (titleDim.placement === 'above') {
            wrapperStyles.flexDirection = 'column';
        }
        else {
            wrapperStyles.flexDirection = 'row';
            titleStyles.width = titleDim.width + "px";
            titleStyles.textAlign = 'right';
            titleStyles.paddingRight = '10px';
        }
    }
    return {
        wrapper: wrapperStyles,
        title: titleStyles,
    };
}
function calculateBarAndValueDimensions(props) {
    var height = props.height, width = props.width;
    var titleDim = calculateTitleDimensions(props);
    var maxBarHeight = 0;
    var maxBarWidth = 0;
    var valueHeight = 0;
    var valueWidth = 0;
    var wrapperWidth = 0;
    var wrapperHeight = 0;
    if (isVertical(props)) {
        valueHeight = Math.min(Math.max(height * 0.1, MIN_VALUE_HEIGHT), MAX_VALUE_HEIGHT);
        valueWidth = width;
        maxBarHeight = height - (titleDim.height + valueHeight);
        maxBarWidth = width;
        wrapperWidth = width;
        wrapperHeight = height - titleDim.height;
    }
    else {
        valueHeight = height - titleDim.height;
        valueWidth = Math.max(Math.min(width * 0.2, MAX_VALUE_WIDTH), MIN_VALUE_WIDTH);
        maxBarHeight = height - titleDim.height;
        maxBarWidth = width - valueWidth - titleDim.width;
        if (titleDim.placement === 'above') {
            wrapperWidth = width;
            wrapperHeight = height - titleDim.height;
        }
        else {
            wrapperWidth = width - titleDim.width;
            wrapperHeight = height;
        }
    }
    return {
        valueWidth: valueWidth,
        valueHeight: valueHeight,
        maxBarWidth: maxBarWidth,
        maxBarHeight: maxBarHeight,
        wrapperHeight: wrapperHeight,
        wrapperWidth: wrapperWidth,
    };
}
function getValuePercent(value, minValue, maxValue) {
    return Math.min((value - minValue) / (maxValue - minValue), 1);
}
/**
 * Only exported to for unit test
 */
function getBasicAndGradientStyles(props) {
    var displayMode = props.displayMode, maxValue = props.maxValue, minValue = props.minValue, value = props.value;
    var _a = calculateBarAndValueDimensions(props), valueWidth = _a.valueWidth, valueHeight = _a.valueHeight, maxBarHeight = _a.maxBarHeight, maxBarWidth = _a.maxBarWidth;
    var valuePercent = getValuePercent(value.numeric, minValue, maxValue);
    var valueColor = getValueColor(props);
    var valueStyles = getValueStyles(value.text, valueColor, valueWidth, valueHeight);
    var isBasic = displayMode === 'basic';
    var wrapperStyles = {
        display: 'flex',
    };
    var barStyles = {
        borderRadius: '3px',
    };
    if (isVertical(props)) {
        var barHeight = Math.max(valuePercent * maxBarHeight, 1);
        // vertical styles
        wrapperStyles.flexDirection = 'column';
        wrapperStyles.justifyContent = 'flex-end';
        barStyles.transition = 'height 1s';
        barStyles.height = barHeight + "px";
        barStyles.width = maxBarWidth + "px";
        // value styles centered
        valueStyles.justifyContent = 'center';
        if (isBasic) {
            // Basic styles
            barStyles.background = "" + tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(valueColor)
                .setAlpha(0.25)
                .toRgbString();
            barStyles.borderTop = "2px solid " + valueColor;
        }
        else {
            // Gradient styles
            barStyles.background = getBarGradient(props, maxBarHeight);
        }
    }
    else {
        var barWidth = Math.max(valuePercent * maxBarWidth, 1);
        // Custom styles for horizontal orientation
        wrapperStyles.flexDirection = 'row-reverse';
        wrapperStyles.justifyContent = 'flex-end';
        wrapperStyles.alignItems = 'center';
        barStyles.transition = 'width 1s';
        barStyles.height = maxBarHeight + "px";
        barStyles.width = barWidth + "px";
        valueStyles.paddingLeft = '10px';
        if (isBasic) {
            // Basic styles
            barStyles.background = "" + tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(valueColor)
                .setAlpha(0.25)
                .toRgbString();
            barStyles.borderRight = "2px solid " + valueColor;
        }
        else {
            // Gradient styles
            barStyles.background = getBarGradient(props, maxBarWidth);
        }
    }
    return {
        wrapper: wrapperStyles,
        bar: barStyles,
        value: valueStyles,
    };
}
/**
 * Only exported to for unit test
 */
function getBarGradient(props, maxSize) {
    var minValue = props.minValue, maxValue = props.maxValue, thresholds = props.thresholds, value = props.value;
    var cssDirection = isVertical(props) ? '0deg' : '90deg';
    var gradient = '';
    var lastpos = 0;
    for (var i = 0; i < thresholds.length; i++) {
        var threshold = thresholds[i];
        var color = Object(_utils__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])(threshold.color);
        var valuePercent = getValuePercent(threshold.value, minValue, maxValue);
        var pos = valuePercent * maxSize;
        var offset = Math.round(pos - (pos - lastpos) / 2);
        if (gradient === '') {
            gradient = "linear-gradient(" + cssDirection + ", " + color + ", " + color;
        }
        else if (value.numeric < threshold.value) {
            break;
        }
        else {
            lastpos = pos;
            gradient += " " + offset + "px, " + color;
        }
    }
    return gradient + ')';
}
/**
 * Only exported to for unit test
 */
function getValueColor(props) {
    var thresholds = props.thresholds, theme = props.theme, value = props.value;
    var activeThreshold = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["getActiveThreshold"])(value.numeric, thresholds);
    if (activeThreshold !== null) {
        return Object(_utils__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])(activeThreshold.color, theme.type);
    }
    return Object(_utils__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])('gray', theme.type);
}
/**
 * Only exported to for unit test
 */
function getValueStyles(value, color, width, height) {
    var heightFont = height / VALUE_LINE_HEIGHT;
    var guess = width / (value.length * 1.1);
    var fontSize = Math.min(Math.max(guess, 14), heightFont);
    return {
        color: color,
        height: height + "px",
        width: width + "px",
        display: 'flex',
        alignItems: 'center',
        lineHeight: VALUE_LINE_HEIGHT,
        fontSize: fontSize.toFixed(4) + 'px',
    };
}
// function getTextWidth(text: string): number {
//   const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
//   var context = canvas.getContext("2d");
//   context.font = "'Roboto', 'Helvetica Neue', Arial, sans-serif";
//   var metrics = context.measureText(text);
//   return metrics.width;
// }


/***/ }),

/***/ "./packages/grafana-ui/src/components/BigValue/BigValue.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/BigValue/BigValue.tsx ***!
  \******************************************************************/
/*! exports provided: BigValue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BigValue", function() { return BigValue; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils */ "./packages/grafana-ui/src/utils/index.ts");
/* harmony import */ var _themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/stylesFactory */ "./packages/grafana-ui/src/themes/stylesFactory.ts");

// Library



// Utils


var getStyles = Object(_themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__["stylesFactory"])(function () {
    return {
        wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      position: 'relative';\n      display: 'table';\n    "], ["\n      position: 'relative';\n      display: 'table';\n    "]))),
        title: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      line-height: 1;\n      text-align: 'center';\n      z-index: 1;\n      display: 'block';\n      width: '100%';\n      position: 'absolute';\n    "], ["\n      line-height: 1;\n      text-align: 'center';\n      z-index: 1;\n      display: 'block';\n      width: '100%';\n      position: 'absolute';\n    "]))),
        value: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      line-height: 1;\n      text-align: 'center';\n      z-index: 1;\n      display: 'table-cell';\n      vertical-align: 'middle';\n      position: 'relative';\n      font-size: '3em';\n      font-weight: 500;\n    "], ["\n      line-height: 1;\n      text-align: 'center';\n      z-index: 1;\n      display: 'table-cell';\n      vertical-align: 'middle';\n      position: 'relative';\n      font-size: '3em';\n      font-weight: 500;\n    "]))),
    };
});
/*
 * This visualization is still in POC state, needed more tests & better structure
 */
var BigValue = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BigValue, _super);
    function BigValue() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.renderText = function (value, padding) {
            if (!value || !value.text) {
                return null;
            }
            var css = {};
            if (padding) {
                css.padding = padding;
            }
            if (value.color) {
                css.color = value.color;
            }
            if (value.fontSize) {
                css.fontSize = value.fontSize;
            }
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { style: css }, value.text);
        };
        return _this;
    }
    BigValue.prototype.componentDidMount = function () {
        this.draw();
    };
    BigValue.prototype.componentDidUpdate = function () {
        this.draw();
    };
    BigValue.prototype.draw = function () {
        var _a = this.props, sparkline = _a.sparkline, theme = _a.theme;
        if (sparkline && this.canvasElement) {
            var data = sparkline.data, minX = sparkline.minX, maxX = sparkline.maxX, fillColor = sparkline.fillColor, lineColor = sparkline.lineColor;
            var options = {
                legend: { show: false },
                series: {
                    lines: {
                        show: true,
                        fill: 1,
                        zero: false,
                        lineWidth: 1,
                        fillColor: Object(_utils__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])(fillColor, theme.type),
                    },
                },
                yaxes: { show: false },
                xaxis: {
                    show: false,
                    min: minX,
                    max: maxX,
                },
                grid: { hoverable: false, show: false },
            };
            var plotSeries = {
                data: data,
                color: Object(_utils__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])(lineColor, theme.type),
            };
            try {
                jquery__WEBPACK_IMPORTED_MODULE_2___default.a.plot(this.canvasElement, [plotSeries], options);
            }
            catch (err) {
                console.log('sparkline rendering error', err, options);
            }
        }
    };
    BigValue.prototype.renderSparkline = function (sparkline) {
        var _this = this;
        var _a = this.props, height = _a.height, width = _a.width;
        var plotCss = {};
        plotCss.position = 'absolute';
        plotCss.bottom = '0px';
        plotCss.left = '0px';
        plotCss.width = width + 'px';
        if (sparkline.full) {
            var dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5;
            plotCss.height = height - dynamicHeightMargin + 'px';
        }
        else {
            plotCss.height = Math.floor(height * 0.25) + 'px';
        }
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: plotCss, ref: function (element) { return (_this.canvasElement = element); } });
    };
    BigValue.prototype.render = function () {
        var _a = this.props, height = _a.height, width = _a.width, value = _a.value, prefix = _a.prefix, suffix = _a.suffix, sparkline = _a.sparkline, backgroundColor = _a.backgroundColor, onClick = _a.onClick, className = _a.className;
        var styles = getStyles();
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])(styles.wrapper, className), style: { width: width, height: height, backgroundColor: backgroundColor }, onClick: onClick },
            value.title && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.title }, value.title),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: styles.value },
                this.renderText(prefix, '0px 2px 0px 0px'),
                this.renderText(value),
                this.renderText(suffix)),
            sparkline && this.renderSparkline(sparkline)));
    };
    return BigValue;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Button/AbstractButton.tsx":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Button/AbstractButton.tsx ***!
  \**********************************************************************/
/*! exports provided: AbstractButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbstractButton", function() { return AbstractButton; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony import */ var _themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/stylesFactory */ "./packages/grafana-ui/src/themes/stylesFactory.ts");






var buttonVariantStyles = function (from, to, textColor, textShadowColor, invert) {
    if (textShadowColor === void 0) { textShadowColor = 'rgba(0, 0, 0, 0.1)'; }
    if (invert === void 0) { invert = false; }
    return Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n  background: linear-gradient(to bottom, ", ", ", ");\n  color: ", ";\n  text-shadow: 0 ", " ", ";\n  &:hover {\n    background: ", ";\n    color: ", ";\n  }\n\n  &:focus {\n    background: ", ";\n    outline: none;\n  }\n"], ["\n  background: linear-gradient(to bottom, ", ", ", ");\n  color: ", ";\n  text-shadow: 0 ", " ", ";\n  &:hover {\n    background: ", ";\n    color: ", ";\n  }\n\n  &:focus {\n    background: ", ";\n    outline: none;\n  }\n"])), from, to, textColor, invert ? '1px' : '-1px', textShadowColor, from, textColor, from);
};
var getButtonStyles = Object(_themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__["stylesFactory"])(function (_a) {
    var theme = _a.theme, size = _a.size, variant = _a.variant, withIcon = _a.withIcon;
    var borderRadius = theme.border.radius.sm;
    var padding, background, fontSize, iconDistance, height, fontWeight = theme.typography.weight.semibold;
    switch (size) {
        case 'sm':
            padding = theme.spacing.xs + " " + theme.spacing.sm;
            fontSize = theme.typography.size.sm;
            iconDistance = theme.spacing.xs;
            height = theme.height.sm;
            break;
        case 'md':
            padding = theme.spacing.sm + " " + theme.spacing.md;
            fontSize = theme.typography.size.md;
            iconDistance = theme.spacing.sm;
            height = theme.height.md;
            break;
        case 'lg':
            padding = theme.spacing.md + " " + theme.spacing.lg;
            fontSize = theme.typography.size.lg;
            fontWeight = theme.typography.weight.regular;
            iconDistance = theme.spacing.sm;
            height = theme.height.lg;
            break;
        default:
            padding = theme.spacing.sm + " " + theme.spacing.md;
            iconDistance = theme.spacing.sm;
            fontSize = theme.typography.size.base;
            height = theme.height.md;
    }
    switch (variant) {
        case 'primary':
            background = buttonVariantStyles(theme.colors.greenBase, theme.colors.greenShade, theme.colors.white);
            break;
        case 'secondary':
            background = buttonVariantStyles(theme.colors.blueBase, theme.colors.blueShade, theme.colors.white);
            break;
        case 'danger':
            background = buttonVariantStyles(theme.colors.redBase, theme.colors.redShade, theme.colors.white);
            break;
        case 'inverse':
            var from = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({ light: theme.colors.gray5, dark: theme.colors.dark6 }, theme.type);
            var to = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
                light: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(from)
                    .darken(5)
                    .toString(),
                dark: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(from)
                    .lighten(4)
                    .toString(),
            }, theme.type);
            background = buttonVariantStyles(from, to, theme.colors.link, 'rgba(0, 0, 0, 0.1)', true);
            break;
        case 'transparent':
            background = Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n        ", ";\n        background: transparent;\n      "], ["\n        ", ";\n        background: transparent;\n      "])), buttonVariantStyles('', '', theme.colors.link, 'rgba(0, 0, 0, 0.1)', true));
            break;
    }
    return {
        button: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: button;\n      display: inline-flex;\n      align-items: center;\n      font-weight: ", ";\n      font-size: ", ";\n      font-family: ", ";\n      line-height: ", ";\n      padding: ", ";\n      text-align: ", ";\n      vertical-align: middle;\n      cursor: pointer;\n      border: none;\n      height: ", ";\n      border-radius: ", ";\n      ", ";\n\n      &[disabled],\n      &:disabled {\n        cursor: not-allowed;\n        opacity: 0.65;\n        box-shadow: none;\n      }\n    "], ["\n      label: button;\n      display: inline-flex;\n      align-items: center;\n      font-weight: ", ";\n      font-size: ", ";\n      font-family: ", ";\n      line-height: ", ";\n      padding: ", ";\n      text-align: ", ";\n      vertical-align: middle;\n      cursor: pointer;\n      border: none;\n      height: ", ";\n      border-radius: ", ";\n      ", ";\n\n      &[disabled],\n      &:disabled {\n        cursor: not-allowed;\n        opacity: 0.65;\n        box-shadow: none;\n      }\n    "])), fontWeight, fontSize, theme.typography.fontFamily.sansSerif, theme.typography.lineHeight.xs, padding, withIcon ? 'left' : 'center', height, borderRadius, background),
        iconWrap: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: button-icon-wrap;\n      display: flex;\n      align-items: center;\n    "], ["\n      label: button-icon-wrap;\n      display: flex;\n      align-items: center;\n    "]))),
        icon: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: button-icon;\n      margin-right: ", ";\n      filter: brightness(100);\n    "], ["\n      label: button-icon;\n      margin-right: ", ";\n      filter: brightness(100);\n    "])), iconDistance),
    };
});
var AbstractButton = function (_a) {
    var renderAs = _a.renderAs, theme = _a.theme, _b = _a.size, size = _b === void 0 ? 'md' : _b, _c = _a.variant, variant = _c === void 0 ? 'primary' : _c, className = _a.className, icon = _a.icon, children = _a.children, otherProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["renderAs", "theme", "size", "variant", "className", "icon", "children"]);
    var buttonStyles = getButtonStyles({ theme: theme, size: size, variant: variant, withIcon: !!icon });
    var nonHtmlProps = {
        theme: theme,
        size: size,
        variant: variant,
    };
    var finalClassName = Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])(buttonStyles.button, className);
    var finalChildren = icon ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: buttonStyles.iconWrap },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])([icon, buttonStyles.icon]) }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, children))) : (children);
    var finalProps = typeof renderAs === 'string'
        ? tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, otherProps, { className: finalClassName, children: finalChildren }) : tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, otherProps, nonHtmlProps, { className: finalClassName, children: finalChildren });
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(renderAs, finalProps);
};
AbstractButton.displayName = 'AbstractButton';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Button/Button.tsx":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Button/Button.tsx ***!
  \**************************************************************/
/*! exports provided: Button, LinkButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return Button; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinkButton", function() { return LinkButton; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _AbstractButton__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AbstractButton */ "./packages/grafana-ui/src/components/Button/AbstractButton.tsx");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");




var Button = function (props) {
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AbstractButton__WEBPACK_IMPORTED_MODULE_2__["AbstractButton"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { renderAs: "button", theme: theme }));
};
Button.displayName = 'Button';
var LinkButton = function (props) {
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AbstractButton__WEBPACK_IMPORTED_MODULE_2__["AbstractButton"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { renderAs: "a", theme: theme }));
};
LinkButton.displayName = 'LinkButton';


/***/ }),

/***/ "./packages/grafana-ui/src/components/CallToActionCard/CallToActionCard.tsx":
/*!**********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/CallToActionCard/CallToActionCard.tsx ***!
  \**********************************************************************************/
/*! exports provided: CallToActionCard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CallToActionCard", function() { return CallToActionCard; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");





var getCallToActionCardStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_4__["stylesFactory"])(function (theme) { return ({
    wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: call-to-action-card;\n    padding: ", ";\n    background: ", ";\n    border-radius: ", ";\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n  "], ["\n    label: call-to-action-card;\n    padding: ", ";\n    background: ", ";\n    border-radius: ", ";\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n  "])), theme.spacing.lg, Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_2__["selectThemeVariant"])({ light: theme.colors.gray6, dark: theme.colors.grayBlue }, theme.type), theme.border.radius.md),
    message: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    margin-bottom: ", ";\n    font-style: italic;\n  "], ["\n    margin-bottom: ", ";\n    font-style: italic;\n  "])), theme.spacing.lg),
    footer: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    margin-top: ", ";\n  "], ["\n    margin-top: ", ";\n  "])), theme.spacing.lg),
}); });
var CallToActionCard = function (_a) {
    var message = _a.message, callToActionElement = _a.callToActionElement, footer = _a.footer, theme = _a.theme, className = _a.className;
    var css = getCallToActionCardStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])([css.wrapper, className]) },
        message && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: css.message }, message),
        callToActionElement,
        footer && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: css.footer }, footer)));
};
var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./packages/grafana-ui/src/components/ClickOutsideWrapper/ClickOutsideWrapper.tsx":
/*!****************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ClickOutsideWrapper/ClickOutsideWrapper.tsx ***!
  \****************************************************************************************/
/*! exports provided: ClickOutsideWrapper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClickOutsideWrapper", function() { return ClickOutsideWrapper; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_2__);



var ClickOutsideWrapper = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ClickOutsideWrapper, _super);
    function ClickOutsideWrapper() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            hasEventListener: false,
        };
        _this.onOutsideClick = function (event) {
            var domNode = react_dom__WEBPACK_IMPORTED_MODULE_2___default.a.findDOMNode(_this);
            if (!domNode || !domNode.contains(event.target)) {
                _this.props.onClick();
            }
        };
        return _this;
    }
    ClickOutsideWrapper.prototype.componentDidMount = function () {
        window.addEventListener('click', this.onOutsideClick, false);
    };
    ClickOutsideWrapper.prototype.componentWillUnmount = function () {
        window.removeEventListener('click', this.onOutsideClick, false);
    };
    ClickOutsideWrapper.prototype.render = function () {
        return this.props.children;
    };
    return ClickOutsideWrapper;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Collapse/Collapse.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Collapse/Collapse.tsx ***!
  \******************************************************************/
/*! exports provided: Collapse */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collapse", function() { return Collapse; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var _themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/stylesFactory */ "./packages/grafana-ui/src/themes/stylesFactory.ts");






var getStyles = Object(_themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__["stylesFactory"])(function (theme) { return ({
    collapse: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse;\n    margin-top: ", ";\n  "], ["\n    label: collapse;\n    margin-top: ", ";\n  "])), theme.spacing.sm),
    collapseBody: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__body;\n    padding: ", "px;\n  "], ["\n    label: collapse__body;\n    padding: ", "px;\n  "])), theme.panelPadding),
    loader: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__loader;\n    height: 2px;\n    position: relative;\n    overflow: hidden;\n    background: none;\n    margin: ", ";\n  "], ["\n    label: collapse__loader;\n    height: 2px;\n    position: relative;\n    overflow: hidden;\n    background: none;\n    margin: ", ";\n  "])), theme.spacing.xs),
    loaderActive: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__loader_active;\n    &:after {\n      content: ' ';\n      display: block;\n      width: 25%;\n      top: 0;\n      top: -50%;\n      height: 250%;\n      position: absolute;\n      animation: loader 2s cubic-bezier(0.17, 0.67, 0.83, 0.67) 500ms;\n      animation-iteration-count: 100;\n      left: -25%;\n      background: ", ";\n    }\n    @keyframes loader {\n      from {\n        left: -25%;\n        opacity: 0.1;\n      }\n      to {\n        left: 100%;\n        opacity: 1;\n      }\n    }\n  "], ["\n    label: collapse__loader_active;\n    &:after {\n      content: ' ';\n      display: block;\n      width: 25%;\n      top: 0;\n      top: -50%;\n      height: 250%;\n      position: absolute;\n      animation: loader 2s cubic-bezier(0.17, 0.67, 0.83, 0.67) 500ms;\n      animation-iteration-count: 100;\n      left: -25%;\n      background: ", ";\n    }\n    @keyframes loader {\n      from {\n        left: -25%;\n        opacity: 0.1;\n      }\n      to {\n        left: 100%;\n        opacity: 1;\n      }\n    }\n  "])), theme.colors.blue),
    header: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__header;\n    padding: ", " ", " 0 ", ";\n    display: flex;\n    cursor: inherit;\n    transition: all 0.1s linear;\n    cursor: pointer;\n  "], ["\n    label: collapse__header;\n    padding: ", " ", " 0 ", ";\n    display: flex;\n    cursor: inherit;\n    transition: all 0.1s linear;\n    cursor: pointer;\n  "])), theme.spacing.sm, theme.spacing.md, theme.spacing.md),
    headerCollapsed: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__header--collapsed;\n    cursor: pointer;\n    padding: ", " ", " 0 ", ";\n  "], ["\n    label: collapse__header--collapsed;\n    cursor: pointer;\n    padding: ", " ", " 0 ", ";\n  "])), theme.spacing.sm, theme.spacing.md, theme.spacing.md),
    headerButtons: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_7 || (templateObject_7 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__header-buttons;\n    margin-right: ", ";\n    font-size: ", ";\n    line-height: ", ";\n    display: inherit;\n  "], ["\n    label: collapse__header-buttons;\n    margin-right: ", ";\n    font-size: ", ";\n    line-height: ", ";\n    display: inherit;\n  "])), theme.spacing.sm, theme.typography.size.lg, theme.typography.heading.h6),
    headerButtonsCollapsed: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_8 || (templateObject_8 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__header-buttons--collapsed;\n    display: none;\n  "], ["\n    label: collapse__header-buttons--collapsed;\n    display: none;\n  "]))),
    headerLabel: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_9 || (templateObject_9 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: collapse__header-label;\n    font-weight: ", ";\n    margin-right: ", ";\n    font-size: ", ";\n    box-shadow: ", ";\n  "], ["\n    label: collapse__header-label;\n    font-weight: ", ";\n    margin-right: ", ";\n    font-size: ", ";\n    box-shadow: ", ";\n  "])), theme.typography.weight.semibold, theme.spacing.sm, theme.typography.heading.h6, Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_3__["selectThemeVariant"])({ light: 'none', dark: '1px 1px 4px rgb(45, 45, 45)' }, theme.type)),
}); });
var Collapse = function (_a) {
    var isOpen = _a.isOpen, label = _a.label, loading = _a.loading, collapsible = _a.collapsible, onToggle = _a.onToggle, children = _a.children;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var style = getStyles(theme);
    var onClickToggle = function () {
        if (onToggle) {
            onToggle(!isOpen);
        }
    };
    var panelClass = Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.collapse, 'panel-container']);
    var iconClass = isOpen ? 'fa fa-caret-up' : 'fa fa-caret-down';
    var loaderClass = loading ? Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.loader, style.loaderActive]) : Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.loader]);
    var headerClass = collapsible ? Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.header]) : Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.headerCollapsed]);
    var headerButtonsClass = collapsible ? Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.headerButtons]) : Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.headerButtonsCollapsed]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: panelClass },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: headerClass, onClick: onClickToggle },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: headerButtonsClass },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: iconClass })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.headerLabel]) }, label)),
        isOpen && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.collapseBody]) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: loaderClass }),
            children))));
};
Collapse.displayName = 'Collapse';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8, templateObject_9;


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/ColorInput.tsx":
/*!***********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/ColorInput.tsx ***!
  \***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/debounce */ "./node_modules/lodash/debounce.js");
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_debounce__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Input_Input__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Input/Input */ "./packages/grafana-ui/src/components/Input/Input.tsx");





var ColorInput = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColorInput, _super);
    function ColorInput(props) {
        var _this = _super.call(this, props) || this;
        _this.updateColor = function (color) {
            _this.props.onChange(color);
        };
        _this.onChange = function (event) {
            var newColor = tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(event.currentTarget.value);
            _this.setState({
                value: event.currentTarget.value,
            });
            if (newColor.isValid()) {
                _this.updateColor(newColor.toString());
            }
        };
        _this.onBlur = function () {
            var newColor = tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(_this.state.value);
            if (!newColor.isValid()) {
                _this.setState({
                    value: _this.props.color,
                });
            }
        };
        _this.state = {
            previousColor: props.color,
            value: props.color,
        };
        _this.updateColor = lodash_debounce__WEBPACK_IMPORTED_MODULE_3___default()(_this.updateColor, 100);
        return _this;
    }
    ColorInput.getDerivedStateFromProps = function (props, state) {
        var newColor = tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(props.color);
        if (newColor.isValid() && props.color !== state.previousColor) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { previousColor: props.color, value: newColor.toString() });
        }
        return state;
    };
    ColorInput.prototype.render = function () {
        var value = this.state.value;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ display: 'flex' }, this.props.style) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                    background: this.props.color,
                    width: '35px',
                    height: '35px',
                    flexGrow: 0,
                    borderRadius: '3px 0 0 3px',
                } }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                    flexGrow: 1,
                } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Input_Input__WEBPACK_IMPORTED_MODULE_4__["Input"], { className: "gf-form-input", value: value, onChange: this.onChange, onBlur: this.onBlur }))));
    };
    return ColorInput;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));
/* harmony default export */ __webpack_exports__["default"] = (ColorInput);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx ***!
  \************************************************************************/
/*! exports provided: colorPickerFactory, ColorPicker, SeriesColorPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorPickerFactory", function() { return colorPickerFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return ColorPicker; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPicker", function() { return SeriesColorPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_omit__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/omit */ "./node_modules/lodash/omit.js");
/* harmony import */ var lodash_omit__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_omit__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Tooltip_PopoverController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Tooltip/PopoverController */ "./packages/grafana-ui/src/components/Tooltip/PopoverController.tsx");
/* harmony import */ var _Tooltip_Popover__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Tooltip/Popover */ "./packages/grafana-ui/src/components/Tooltip/Popover.tsx");
/* harmony import */ var _ColorPickerPopover__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ColorPickerPopover */ "./packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx");
/* harmony import */ var _utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utils/namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony import */ var _SeriesColorPickerPopover__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./SeriesColorPickerPopover */ "./packages/grafana-ui/src/components/ColorPicker/SeriesColorPickerPopover.tsx");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var _ColorPickerTrigger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ColorPickerTrigger */ "./packages/grafana-ui/src/components/ColorPicker/ColorPickerTrigger.tsx");










var colorPickerFactory = function (popover, displayName) {
    if (displayName === void 0) { displayName = 'ColorPicker'; }
    var _a;
    return _a = /** @class */ (function (_super) {
            tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColorPicker, _super);
            function ColorPicker() {
                var _this = _super !== null && _super.apply(this, arguments) || this;
                _this.pickerTriggerRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["createRef"])();
                _this.onColorChange = function (color) {
                    var _a = _this.props, onColorChange = _a.onColorChange, onChange = _a.onChange;
                    var changeHandler = (onColorChange || onChange);
                    return changeHandler(color);
                };
                return _this;
            }
            ColorPicker.prototype.render = function () {
                var _this = this;
                var _a = this.props, theme = _a.theme, children = _a.children;
                var popoverElement = react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(popover, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, lodash_omit__WEBPACK_IMPORTED_MODULE_2___default()(this.props, 'children'), { onChange: this.onColorChange }));
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_PopoverController__WEBPACK_IMPORTED_MODULE_3__["PopoverController"], { content: popoverElement, hideAfter: 300 }, function (showPopper, hidePopper, popperProps) {
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                        _this.pickerTriggerRef.current && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_Popover__WEBPACK_IMPORTED_MODULE_4__["Popover"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, popperProps, { referenceElement: _this.pickerTriggerRef.current, wrapperClassName: "ColorPicker", onMouseLeave: hidePopper, onMouseEnter: showPopper }))),
                        children ? (
                        // Children have a bit weird type due to intersection used in the definition so we need to cast here,
                        // but the definition is correct and should not allow to pass a children that does not conform to
                        // ColorPickerTriggerRenderer type.
                        children({
                            ref: _this.pickerTriggerRef,
                            showColorPicker: showPopper,
                            hideColorPicker: hidePopper,
                        })) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ColorPickerTrigger__WEBPACK_IMPORTED_MODULE_9__["ColorPickerTrigger"], { ref: _this.pickerTriggerRef, onClick: showPopper, onMouseLeave: hidePopper, color: Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_6__["getColorFromHexRgbOrName"])(_this.props.color || '#000000', theme.type) }))));
                }));
            };
            return ColorPicker;
        }(react__WEBPACK_IMPORTED_MODULE_1__["Component"])),
        _a.displayName = displayName,
        _a;
};
var ColorPicker = Object(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_8__["withTheme"])(colorPickerFactory(_ColorPickerPopover__WEBPACK_IMPORTED_MODULE_5__["ColorPickerPopover"], 'ColorPicker'));
var SeriesColorPicker = Object(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_8__["withTheme"])(colorPickerFactory(_SeriesColorPickerPopover__WEBPACK_IMPORTED_MODULE_7__["SeriesColorPickerPopover"], 'SeriesColorPicker'));


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx":
/*!*******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx ***!
  \*******************************************************************************/
/*! exports provided: ColorPickerPopover */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPickerPopover", function() { return ColorPickerPopover; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _NamedColorsPalette__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NamedColorsPalette */ "./packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx");
/* harmony import */ var _utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony import */ var _SpectrumPalette__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SpectrumPalette */ "./packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx");
/* harmony import */ var _types_theme__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../types/theme */ "./packages/grafana-ui/src/types/theme.ts");
/* harmony import */ var _warnAboutColorPickerPropsDeprecation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./warnAboutColorPickerPropsDeprecation */ "./packages/grafana-ui/src/components/ColorPicker/warnAboutColorPickerPropsDeprecation.ts");







var ColorPickerPopover = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColorPickerPopover, _super);
    function ColorPickerPopover(props) {
        var _this = _super.call(this, props) || this;
        _this.getTabClassName = function (tabName) {
            var activePicker = _this.state.activePicker;
            return "ColorPickerPopover__tab " + (activePicker === tabName && 'ColorPickerPopover__tab--active');
        };
        _this.handleChange = function (color) {
            var _a = _this.props, onColorChange = _a.onColorChange, onChange = _a.onChange, enableNamedColors = _a.enableNamedColors, theme = _a.theme;
            var changeHandler = onColorChange || onChange;
            if (enableNamedColors) {
                return changeHandler(color);
            }
            changeHandler(Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(color, theme.type));
        };
        _this.onTabChange = function (tab) {
            return function () { return _this.setState({ activePicker: tab }); };
        };
        _this.renderPicker = function () {
            var activePicker = _this.state.activePicker;
            var _a = _this.props, color = _a.color, theme = _a.theme;
            switch (activePicker) {
                case 'spectrum':
                    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_SpectrumPalette__WEBPACK_IMPORTED_MODULE_4__["default"], { color: color, onChange: _this.handleChange, theme: theme });
                case 'palette':
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_NamedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["NamedColorsPalette"], { color: Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__["getColorName"])(color, theme.type), onChange: _this.handleChange, theme: theme }));
                default:
                    return _this.renderCustomPicker(activePicker);
            }
        };
        _this.renderCustomPicker = function (tabKey) {
            var _a = _this.props, customPickers = _a.customPickers, color = _a.color, theme = _a.theme;
            if (!customPickers) {
                return null;
            }
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(customPickers[tabKey].tabComponent, {
                color: color,
                theme: theme,
                onChange: _this.handleChange,
            });
        };
        _this.renderCustomPickerTabs = function () {
            var customPickers = _this.props.customPickers;
            if (!customPickers) {
                return null;
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, Object.keys(customPickers).map(function (key) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: _this.getTabClassName(key), onClick: _this.onTabChange(key), key: key }, customPickers[key].name));
            })));
        };
        _this.state = {
            activePicker: 'palette',
        };
        Object(_warnAboutColorPickerPropsDeprecation__WEBPACK_IMPORTED_MODULE_6__["warnAboutColorPickerPropsDeprecation"])('ColorPickerPopover', props);
        return _this;
    }
    ColorPickerPopover.prototype.render = function () {
        var theme = this.props.theme;
        var colorPickerTheme = theme.type || _types_theme__WEBPACK_IMPORTED_MODULE_5__["GrafanaThemeType"].Dark;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "ColorPickerPopover ColorPickerPopover--" + colorPickerTheme },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "ColorPickerPopover__tabs" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: this.getTabClassName('palette'), onClick: this.onTabChange('palette') }, "Colors"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: this.getTabClassName('spectrum'), onClick: this.onTabChange('spectrum') }, "Custom"),
                this.renderCustomPickerTabs()),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "ColorPickerPopover__content" }, this.renderPicker())));
    };
    return ColorPickerPopover;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/ColorPickerTrigger.tsx":
/*!*******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/ColorPickerTrigger.tsx ***!
  \*******************************************************************************/
/*! exports provided: ColorPickerTrigger */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPickerTrigger", function() { return ColorPickerTrigger; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var ColorPickerTrigger = Object(react__WEBPACK_IMPORTED_MODULE_0__["forwardRef"])(function ColorPickerTrigger(props, ref) {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { ref: ref, onClick: props.onClick, onMouseLeave: props.onMouseLeave, style: {
            overflow: 'hidden',
            background: 'inherit',
            border: 'none',
            color: 'inherit',
            padding: 0,
            borderRadius: 10,
            cursor: 'pointer',
        } },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { style: {
                position: 'relative',
                width: 15,
                height: 15,
                border: 'none',
                margin: 0,
                float: 'left',
                zIndex: 0,
                backgroundImage: 
                // tslint:disable-next-line:max-line-length
                'url(data:image/png,base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAIAAADZF8uwAAAAGUlEQVQYV2M4gwH+YwCGIasIUwhT25BVBADtzYNYrHvv4gAAAABJRU5ErkJggg==)',
            } },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { style: {
                    backgroundColor: props.color,
                    display: 'block',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    bottom: 0,
                    right: 0,
                } }))));
});


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx":
/*!*****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx ***!
  \*****************************************************************************/
/*! exports provided: ColorSwatchVariant, ColorSwatch, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorSwatchVariant", function() { return ColorSwatchVariant; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorSwatch", function() { return ColorSwatch; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony import */ var lodash_upperFirst__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/upperFirst */ "./node_modules/lodash/upperFirst.js");
/* harmony import */ var lodash_upperFirst__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_upperFirst__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash_find__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash/find */ "./node_modules/lodash/find.js");
/* harmony import */ var lodash_find__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash_find__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");






var ColorSwatchVariant;
(function (ColorSwatchVariant) {
    ColorSwatchVariant["Small"] = "small";
    ColorSwatchVariant["Large"] = "large";
})(ColorSwatchVariant || (ColorSwatchVariant = {}));
var ColorSwatch = function (_a) {
    var color = _a.color, label = _a.label, _b = _a.variant, variant = _b === void 0 ? ColorSwatchVariant.Small : _b, isSelected = _a.isSelected, theme = _a.theme, otherProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["color", "label", "variant", "isSelected", "theme"]);
    var isSmall = variant === ColorSwatchVariant.Small;
    var swatchSize = isSmall ? '16px' : '32px';
    var selectedSwatchBorder = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_5__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.black,
    }, theme.type);
    var swatchStyles = {
        width: swatchSize,
        height: swatchSize,
        borderRadius: '50%',
        background: "" + color,
        marginRight: isSmall ? '0px' : '8px',
        boxShadow: isSelected ? "inset 0 0 0 2px " + color + ", inset 0 0 0 4px " + selectedSwatchBorder : 'none',
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ style: {
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer',
        } }, otherProps),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: swatchStyles }),
        variant === ColorSwatchVariant.Large && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, label)));
};
var NamedColorsGroup = function (_a) {
    var colors = _a.colors, selectedColor = _a.selectedColor, onColorSelect = _a.onColorSelect, theme = _a.theme, otherProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["colors", "selectedColor", "onColorSelect", "theme"]);
    var primaryColor = lodash_find__WEBPACK_IMPORTED_MODULE_4___default()(colors, function (color) { return !!color.isPrimary; });
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, otherProps, { style: { display: 'flex', flexDirection: 'column' } }),
        primaryColor && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ColorSwatch, { key: primaryColor.name, isSelected: primaryColor.name === selectedColor, variant: ColorSwatchVariant.Large, color: Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorForTheme"])(primaryColor, theme.type), label: lodash_upperFirst__WEBPACK_IMPORTED_MODULE_3___default()(primaryColor.hue), onClick: function () { return onColorSelect(primaryColor); }, theme: theme })),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                display: 'flex',
                marginTop: '8px',
            } }, colors.map(function (color) {
            return !color.isPrimary && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { key: color.name, style: { marginRight: '4px' } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ColorSwatch, { key: color.name, isSelected: color.name === selectedColor, color: Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorForTheme"])(color, theme.type), onClick: function () { return onColorSelect(color); }, theme: theme })));
        }))));
};
/* harmony default export */ __webpack_exports__["default"] = (NamedColorsGroup);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx":
/*!*******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx ***!
  \*******************************************************************************/
/*! exports provided: NamedColorsPalette */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NamedColorsPalette", function() { return NamedColorsPalette; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony import */ var _NamedColorsGroup__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NamedColorsGroup */ "./packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx");



var NamedColorsPalette = function (_a) {
    var color = _a.color, onChange = _a.onChange, theme = _a.theme;
    var swatches = [];
    Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_1__["getNamedColorPalette"])().forEach(function (colors, hue) {
        swatches.push(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_NamedColorsGroup__WEBPACK_IMPORTED_MODULE_2__["default"], { key: hue, theme: theme, selectedColor: color, colors: colors, onColorSelect: function (color) {
                onChange(color.name);
            } }));
    });
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { style: {
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gridRowGap: '24px',
            gridColumnGap: '24px',
        } }, swatches));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/SeriesColorPickerPopover.tsx":
/*!*************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/SeriesColorPickerPopover.tsx ***!
  \*************************************************************************************/
/*! exports provided: SeriesColorPickerPopover, AxisSelector, SeriesColorPickerPopoverWithTheme */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPickerPopover", function() { return SeriesColorPickerPopover; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisSelector", function() { return AxisSelector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPickerPopoverWithTheme", function() { return SeriesColorPickerPopoverWithTheme; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _ColorPickerPopover__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ColorPickerPopover */ "./packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx");
/* harmony import */ var _Switch_Switch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Switch/Switch */ "./packages/grafana-ui/src/components/Switch/Switch.tsx");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");





var SeriesColorPickerPopover = function (props) {
    var yaxis = props.yaxis, onToggleAxis = props.onToggleAxis, color = props.color, colorPickerProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](props, ["yaxis", "onToggleAxis", "color"]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ColorPickerPopover__WEBPACK_IMPORTED_MODULE_2__["ColorPickerPopover"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, colorPickerProps, { color: color || '#000000', customPickers: {
            yaxis: {
                name: 'Y-Axis',
                tabComponent: function () { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Switch_Switch__WEBPACK_IMPORTED_MODULE_3__["Switch"], { key: "yaxisSwitch", label: "Use right y-axis", className: "ColorPicker__axisSwitch", labelClass: "ColorPicker__axisSwitchLabel", checked: yaxis === 2, onChange: function () {
                        if (onToggleAxis) {
                            onToggleAxis();
                        }
                    } })); },
            },
        } })));
};
var AxisSelector = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AxisSelector, _super);
    function AxisSelector(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            yaxis: _this.props.yaxis,
        };
        _this.onToggleAxis = _this.onToggleAxis.bind(_this);
        return _this;
    }
    AxisSelector.prototype.onToggleAxis = function () {
        this.setState({
            yaxis: this.state.yaxis === 2 ? 1 : 2,
        });
        if (this.props.onToggleAxis) {
            this.props.onToggleAxis();
        }
    };
    AxisSelector.prototype.render = function () {
        var leftButtonClass = this.state.yaxis === 1 ? 'btn-primary' : 'btn-inverse';
        var rightButtonClass = this.state.yaxis === 2 ? 'btn-primary' : 'btn-inverse';
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "p-b-1" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "small p-r-1" }, "Y Axis:"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { onClick: this.onToggleAxis, className: 'btn btn-small ' + leftButtonClass }, "Left"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { onClick: this.onToggleAxis, className: 'btn btn-small ' + rightButtonClass }, "Right")));
    };
    return AxisSelector;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));

// This component is to enable SeriecColorPickerPopover usage via series-color-picker-popover directive
var SeriesColorPickerPopoverWithTheme = Object(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_4__["withTheme"])(SeriesColorPickerPopover);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx ***!
  \****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-color */ "./node_modules/react-color/lib/index.js");
/* harmony import */ var react_color__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_color__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_color_lib_components_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-color/lib/components/common */ "./node_modules/react-color/lib/components/common/index.js");
/* harmony import */ var react_color_lib_components_common__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_color_lib_components_common__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils/namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _ColorInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ColorInput */ "./packages/grafana-ui/src/components/ColorPicker/ColorInput.tsx");
/* harmony import */ var _SpectrumPalettePointer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./SpectrumPalettePointer */ "./packages/grafana-ui/src/components/ColorPicker/SpectrumPalettePointer.tsx");








var renderPointer = function (theme) { return function (props) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_SpectrumPalettePointer__WEBPACK_IMPORTED_MODULE_7__["default"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { theme: theme }))); }; };
// @ts-ignore
var SpectrumPicker = Object(react_color__WEBPACK_IMPORTED_MODULE_2__["CustomPicker"])(function (_a) {
    var rgb = _a.rgb, hsl = _a.hsl, onChange = _a.onChange, theme = _a.theme;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
            display: 'flex',
            width: '100%',
            flexDirection: 'column',
        } },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                display: 'flex',
            } },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                    display: 'flex',
                    flexGrow: 1,
                    flexDirection: 'column',
                } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                        position: 'relative',
                        height: '100px',
                        width: '100%',
                    } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_color_lib_components_common__WEBPACK_IMPORTED_MODULE_3__["Saturation"], { onChange: onChange, hsl: hsl, hsv: tinycolor2__WEBPACK_IMPORTED_MODULE_5___default()(hsl).toHsv() })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                        width: '100%',
                        height: '16px',
                        marginTop: '16px',
                        position: 'relative',
                        background: 'white',
                    } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_color_lib_components_common__WEBPACK_IMPORTED_MODULE_3__["Alpha"], { rgb: rgb, hsl: hsl, a: rgb.a, onChange: onChange, pointer: renderPointer(theme) }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                    position: 'relative',
                    width: '16px',
                    height: '100px',
                    marginLeft: '16px',
                } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_color_lib_components_common__WEBPACK_IMPORTED_MODULE_3__["Hue"], { onChange: onChange, hsl: hsl, direction: "vertical", pointer: renderPointer(theme) })))));
});
var SpectrumPalette = function (_a) {
    var color = _a.color, onChange = _a.onChange, theme = _a.theme;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(SpectrumPicker, { color: tinycolor2__WEBPACK_IMPORTED_MODULE_5___default()(Object(_utils_namedColorsPalette__WEBPACK_IMPORTED_MODULE_4__["getColorFromHexRgbOrName"])(color)).toRgb(), onChange: function (a) {
                onChange(tinycolor2__WEBPACK_IMPORTED_MODULE_5___default()(a.rgb).toString());
            }, theme: theme }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ColorInput__WEBPACK_IMPORTED_MODULE_6__["default"], { theme: theme, color: color, onChange: onChange, style: { marginTop: '16px' } })));
};
/* harmony default export */ __webpack_exports__["default"] = (SpectrumPalette);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/SpectrumPalettePointer.tsx":
/*!***********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/SpectrumPalettePointer.tsx ***!
  \***********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");



var SpectrumPalettePointer = function (_a) {
    var theme = _a.theme, direction = _a.direction;
    var styles = {
        picker: {
            width: '16px',
            height: '16px',
            transform: direction === 'vertical' ? 'translate(0, -8px)' : 'translate(-8px, 0)',
        },
    };
    var pointerColor = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_2__["selectThemeVariant"])({
        light: theme.colors.dark3,
        dark: theme.colors.gray2,
    }, theme.type);
    var pointerStyles = {
        position: 'absolute',
        left: '6px',
        width: '0',
        height: '0',
        borderStyle: 'solid',
        background: 'none',
    };
    var topArrowStyles = {
        top: '-7px',
        borderWidth: '6px 3px 0px 3px',
        borderColor: pointerColor + " transparent transparent transparent",
    };
    var bottomArrowStyles = {
        bottom: '-7px',
        borderWidth: '0px 3px 6px 3px',
        borderColor: " transparent transparent " + pointerColor + " transparent",
    };
    if (direction === 'vertical') {
        pointerStyles = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, pointerStyles, { left: 'auto' });
        topArrowStyles = {
            borderWidth: '3px 0px 3px 6px',
            borderColor: "transparent transparent transparent " + pointerColor,
            left: '-7px',
            top: '7px',
        };
        bottomArrowStyles = {
            borderWidth: '3px 6px 3px 0px',
            borderColor: "transparent " + pointerColor + " transparent transparent",
            right: '-7px',
            top: '7px',
        };
    }
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: styles.picker },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, pointerStyles, topArrowStyles) }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, pointerStyles, bottomArrowStyles) })));
};
/* harmony default export */ __webpack_exports__["default"] = (SpectrumPalettePointer);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ColorPicker/warnAboutColorPickerPropsDeprecation.ts":
/*!************************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ColorPicker/warnAboutColorPickerPropsDeprecation.ts ***!
  \************************************************************************************************/
/*! exports provided: warnAboutColorPickerPropsDeprecation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "warnAboutColorPickerPropsDeprecation", function() { return warnAboutColorPickerPropsDeprecation; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

var warnAboutColorPickerPropsDeprecation = function (componentName, props) {
    var onColorChange = props.onColorChange;
    if (onColorChange) {
        Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["deprecationWarning"])(componentName, 'onColorChange', 'onChange');
    }
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/ContextMenu/ContextMenu.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ContextMenu/ContextMenu.tsx ***!
  \************************************************************************/
/*! exports provided: ContextMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContextMenu", function() { return ContextMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-use/lib/useClickAway */ "./node_modules/react-use/lib/useClickAway.js");
/* harmony import */ var react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../index */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/stylesFactory */ "./packages/grafana-ui/src/themes/stylesFactory.ts");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");







var getContextMenuStyles = Object(_themes_stylesFactory__WEBPACK_IMPORTED_MODULE_5__["stylesFactory"])(function (theme) {
    var linkColor = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.dark2,
        dark: theme.colors.text,
    }, theme.type);
    var linkColorHover = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.link,
        dark: theme.colors.white,
    }, theme.type);
    var wrapperBg = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray7,
        dark: theme.colors.dark2,
    }, theme.type);
    var wrapperShadow = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray3,
        dark: theme.colors.black,
    }, theme.type);
    var itemColor = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.black,
        dark: theme.colors.white,
    }, theme.type);
    var groupLabelColor = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray1,
        dark: theme.colors.textWeak,
    }, theme.type);
    var itemBgHover = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray5,
        dark: theme.colors.dark7,
    }, theme.type);
    var headerBg = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.dark1,
    }, theme.type);
    var headerSeparator = Object(_index__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.dark7,
    }, theme.type);
    return {
        header: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      padding: 4px;\n      border-bottom: 1px solid ", ";\n      background: ", ";\n      margin-bottom: ", ";\n      border-radius: ", " ", " 0 0;\n    "], ["\n      padding: 4px;\n      border-bottom: 1px solid ", ";\n      background: ", ";\n      margin-bottom: ", ";\n      border-radius: ", " ", " 0 0;\n    "])), headerSeparator, headerBg, theme.spacing.xs, theme.border.radius.sm, theme.border.radius.sm),
        wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      background: ", ";\n      z-index: 1;\n      box-shadow: 0 2px 5px 0 ", ";\n      min-width: 200px;\n      display: inline-block;\n      border-radius: ", ";\n    "], ["\n      background: ", ";\n      z-index: 1;\n      box-shadow: 0 2px 5px 0 ", ";\n      min-width: 200px;\n      display: inline-block;\n      border-radius: ", ";\n    "])), wrapperBg, wrapperShadow, theme.border.radius.sm),
        link: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      color: ", ";\n      display: flex;\n      cursor: pointer;\n      &:hover {\n        color: ", ";\n        text-decoration: none;\n      }\n    "], ["\n      color: ", ";\n      display: flex;\n      cursor: pointer;\n      &:hover {\n        color: ", ";\n        text-decoration: none;\n      }\n    "])), linkColor, linkColorHover),
        item: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      background: none;\n      padding: 4px 8px;\n      color: ", ";\n      border-left: 2px solid transparent;\n      cursor: pointer;\n      &:hover {\n        background: ", ";\n        border-image: linear-gradient(#f05a28 30%, #fbca0a 99%);\n        border-image-slice: 1;\n      }\n    "], ["\n      background: none;\n      padding: 4px 8px;\n      color: ", ";\n      border-left: 2px solid transparent;\n      cursor: pointer;\n      &:hover {\n        background: ", ";\n        border-image: linear-gradient(#f05a28 30%, #fbca0a 99%);\n        border-image-slice: 1;\n      }\n    "])), itemColor, itemBgHover),
        groupLabel: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      color: ", ";\n      font-size: ", ";\n      line-height: ", ";\n      padding: ", " ", ";\n    "], ["\n      color: ", ";\n      font-size: ", ";\n      line-height: ", ";\n      padding: ", " ", ";\n    "])), groupLabelColor, theme.typography.size.sm, theme.typography.lineHeight.lg, theme.spacing.xs, theme.spacing.sm),
        icon: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      opacity: 0.7;\n      width: 12px;\n      height: 12px;\n      display: inline-block;\n      margin-right: 10px;\n      color: ", ";\n      position: relative;\n      top: 4px;\n    "], ["\n      opacity: 0.7;\n      width: 12px;\n      height: 12px;\n      display: inline-block;\n      margin-right: 10px;\n      color: ", ";\n      position: relative;\n      top: 4px;\n    "])), theme.colors.linkDisabled),
    };
});
var ContextMenu = react__WEBPACK_IMPORTED_MODULE_1___default.a.memo(function (_a) {
    var x = _a.x, y = _a.y, onClose = _a.onClose, items = _a.items, renderHeader = _a.renderHeader;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var menuRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["useRef"])(null);
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])({}), 2), positionStyles = _b[0], setPositionStyles = _b[1];
    Object(react__WEBPACK_IMPORTED_MODULE_1__["useLayoutEffect"])(function () {
        var menuElement = menuRef.current;
        if (menuElement) {
            var rect = menuElement.getBoundingClientRect();
            var OFFSET = 5;
            var collisions = {
                right: window.innerWidth < x + rect.width,
                bottom: window.innerHeight < rect.bottom + rect.height + OFFSET,
            };
            setPositionStyles({
                position: 'fixed',
                left: collisions.right ? x - rect.width - OFFSET : x - OFFSET,
                top: collisions.bottom ? y - rect.height - OFFSET : y + OFFSET,
            });
        }
    }, [menuRef.current]);
    react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_3___default()(menuRef, function () {
        if (onClose) {
            onClose();
        }
    });
    var styles = getContextMenuStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_6__["Portal"], null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: menuRef, style: positionStyles, className: styles.wrapper },
            renderHeader && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.header }, renderHeader()),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_6__["List"], { items: items || [], renderItem: function (item, index) {
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ContextMenuGroup, { group: item, onItemClick: onClose })));
                } }))));
});
var ContextMenuItem = react__WEBPACK_IMPORTED_MODULE_1___default.a.memo(function (_a) {
    var url = _a.url, icon = _a.icon, label = _a.label, target = _a.target, onClick = _a.onClick, className = _a.className;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var styles = getContextMenuStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.item },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: url, target: target || '_self', className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(className, styles.link), onClick: function (e) {
                if (onClick) {
                    onClick(e);
                }
            } },
            icon && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])("" + icon, styles.icon) }),
            " ",
            label)));
});
var ContextMenuGroup = function (_a) {
    var group = _a.group, onItemClick = _a.onItemClick;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var styles = getContextMenuStyles(theme);
    if (group.items.length === 0) {
        return null;
    }
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
        group.label && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.groupLabel }, group.label),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_6__["List"], { items: group.items || [], renderItem: function (item) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ContextMenuItem, { url: item.url, label: item.label, target: item.target, icon: item.icon, onClick: function (e) {
                        if (item.onClick) {
                            item.onClick(e);
                        }
                        if (onItemClick) {
                            onItemClick();
                        }
                    } }));
            } })));
};
ContextMenu.displayName = 'ContextMenu';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6;


/***/ }),

/***/ "./packages/grafana-ui/src/components/ContextMenu/WithContextMenu.tsx":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ContextMenu/WithContextMenu.tsx ***!
  \****************************************************************************/
/*! exports provided: WithContextMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WithContextMenu", function() { return WithContextMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../ContextMenu/ContextMenu */ "./packages/grafana-ui/src/components/ContextMenu/ContextMenu.tsx");



var WithContextMenu = function (_a) {
    var children = _a.children, getContextMenuItems = _a.getContextMenuItems;
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(false), 2), isMenuOpen = _b[0], setIsMenuOpen = _b[1];
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])({ x: 0, y: 0 }), 2), menuPosition = _c[0], setMenuPositon = _c[1];
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        children({
            openMenu: function (e) {
                setIsMenuOpen(true);
                setMenuPositon({
                    x: e.pageX,
                    y: e.pageY,
                });
            },
        }),
        isMenuOpen && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_2__["ContextMenu"], { onClose: function () { return setIsMenuOpen(false); }, x: menuPosition.x, y: menuPosition.y, items: getContextMenuItems() }))));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx":
/*!********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx ***!
  \********************************************************************************/
/*! exports provided: CustomScrollbar, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomScrollbar", function() { return CustomScrollbar; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_isNil__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/isNil */ "./node_modules/lodash/isNil.js");
/* harmony import */ var lodash_isNil__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_isNil__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var react_custom_scrollbars__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-custom-scrollbars */ "./node_modules/react-custom-scrollbars/lib/index.js");
/* harmony import */ var react_custom_scrollbars__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_custom_scrollbars__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");






/**
 * Wraps component into <Scrollbars> component from `react-custom-scrollbars`
 */
var CustomScrollbar = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CustomScrollbar, _super);
    function CustomScrollbar(props) {
        var _this = _super.call(this, props) || this;
        _this.renderTrack = function (track, hideTrack, passedProps) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, passedProps, { className: Object(emotion__WEBPACK_IMPORTED_MODULE_5__["cx"])(Object(emotion__WEBPACK_IMPORTED_MODULE_5__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n            visibility: ", ";\n          "], ["\n            visibility: ", ";\n          "])), hideTrack ? 'hidden' : 'visible'), track) })));
        };
        _this.renderThumb = function (thumb, passedProps) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, passedProps, { className: thumb }));
        };
        _this.renderTrackHorizontal = function (passedProps) {
            return _this.renderTrack('track-horizontal', _this.props.hideHorizontalTrack, passedProps);
        };
        _this.renderTrackVertical = function (passedProps) {
            return _this.renderTrack('track-vertical', _this.props.hideVerticalTrack, passedProps);
        };
        _this.renderThumbHorizontal = function (passedProps) {
            return _this.renderThumb('thumb-horizontal', passedProps);
        };
        _this.renderThumbVertical = function (passedProps) {
            return _this.renderThumb('thumb-vertical', passedProps);
        };
        _this.renderView = function (passedProps) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, passedProps, { className: "view" }));
        };
        _this.ref = react__WEBPACK_IMPORTED_MODULE_1___default.a.createRef();
        return _this;
    }
    CustomScrollbar.prototype.updateScroll = function () {
        var ref = this.ref.current;
        var scrollTop = this.props.scrollTop;
        if (ref && !lodash_isNil__WEBPACK_IMPORTED_MODULE_2___default()(scrollTop)) {
            ref.scrollTop(scrollTop);
        }
    };
    CustomScrollbar.prototype.componentDidMount = function () {
        var _this = this;
        this.updateScroll();
        // this logic is to make scrollbar visible when content is added body after mount
        if (this.props.updateAfterMountMs) {
            setTimeout(function () { return _this.updateAfterMount(); }, this.props.updateAfterMountMs);
        }
    };
    CustomScrollbar.prototype.updateAfterMount = function () {
        if (this.ref && this.ref.current) {
            var scrollbar = this.ref.current;
            if (scrollbar.update) {
                scrollbar.update();
            }
        }
    };
    CustomScrollbar.prototype.componentDidUpdate = function () {
        this.updateScroll();
    };
    CustomScrollbar.prototype.render = function () {
        var _a = this.props, className = _a.className, children = _a.children, autoHeightMax = _a.autoHeightMax, autoHeightMin = _a.autoHeightMin, setScrollTop = _a.setScrollTop, autoHide = _a.autoHide, autoHideTimeout = _a.autoHideTimeout, hideTracksWhenNotNeeded = _a.hideTracksWhenNotNeeded;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_custom_scrollbars__WEBPACK_IMPORTED_MODULE_4___default.a, { ref: this.ref, className: classnames__WEBPACK_IMPORTED_MODULE_3___default()('custom-scrollbar', className), onScroll: setScrollTop, autoHeight: true, autoHide: autoHide, autoHideTimeout: autoHideTimeout, hideTracksWhenNotNeeded: hideTracksWhenNotNeeded, 
            // These autoHeightMin & autoHeightMax options affect firefox and chrome differently.
            // Before these where set to inhert but that caused problems with cut of legends in firefox
            autoHeightMax: autoHeightMax, autoHeightMin: autoHeightMin, renderTrackHorizontal: this.renderTrackHorizontal, renderTrackVertical: this.renderTrackVertical, renderThumbHorizontal: this.renderThumbHorizontal, renderThumbVertical: this.renderThumbVertical, renderView: this.renderView }, children));
    };
    CustomScrollbar.defaultProps = {
        autoHide: false,
        autoHideTimeout: 200,
        autoHideDuration: 200,
        setScrollTop: function () { },
        hideTracksWhenNotNeeded: false,
        autoHeightMin: '0',
        autoHeightMax: '100%',
    };
    return CustomScrollbar;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

/* harmony default export */ __webpack_exports__["default"] = (CustomScrollbar);
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx":
/*!*************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx ***!
  \*************************************************************************/
/*! exports provided: DataLinkEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLinkEditor", function() { return DataLinkEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/index */ "./packages/grafana-ui/src/themes/index.ts");
/* harmony import */ var _DataLinkInput__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DataLinkInput */ "./packages/grafana-ui/src/components/DataLinks/DataLinkInput.tsx");






var getStyles = Object(_themes_index__WEBPACK_IMPORTED_MODULE_4__["stylesFactory"])(function (theme) { return ({
    listItem: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    margin-bottom: ", ";\n  "], ["\n    margin-bottom: ", ";\n  "])), theme.spacing.sm),
    infoText: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    padding-bottom: ", ";\n    margin-left: 66px;\n    color: ", ";\n  "], ["\n    padding-bottom: ", ";\n    margin-left: 66px;\n    color: ", ";\n  "])), theme.spacing.md, theme.colors.textWeak),
}); });
var DataLinkEditor = react__WEBPACK_IMPORTED_MODULE_1___default.a.memo(function (_a) {
    var index = _a.index, value = _a.value, onChange = _a.onChange, onRemove = _a.onRemove, suggestions = _a.suggestions, isLast = _a.isLast;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_index__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var styles = getStyles(theme);
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(value.title), 2), title = _b[0], setTitle = _b[1];
    var onUrlChange = function (url, callback) {
        onChange(index, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, value, { url: url }), callback);
    };
    var onTitleChange = function (event) {
        setTitle(event.target.value);
    };
    var onTitleBlur = function () {
        onChange(index, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, value, { title: title }));
    };
    var onRemoveClick = function () {
        onRemove(value);
    };
    var onOpenInNewTabChanged = function () {
        onChange(index, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, value, { targetBlank: !value.targetBlank }));
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.listItem },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--inline" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_2__["FormField"], { className: "gf-form--grow", label: "Title", value: title, onChange: onTitleChange, onBlur: onTitleBlur, inputWidth: 0, labelWidth: 5, placeholder: "Show details" }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Open in new tab", checked: value.targetBlank || false, onChange: onOpenInNewTabChanged }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "gf-form-label gf-form-label--btn", onClick: onRemoveClick, title: "Remove link" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-times" }))),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "URL", labelWidth: 5, inputEl: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DataLinkInput__WEBPACK_IMPORTED_MODULE_5__["DataLinkInput"], { value: value.url, onChange: onUrlChange, suggestions: suggestions }), className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n            width: 100%;\n          "], ["\n            width: 100%;\n          "]))) }),
        isLast && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.infoText }, "With data links you can reference data variables like series name, labels and values. Type CMD+Space, CTRL+Space, or $ to open variable suggestions."))));
});
DataLinkEditor.displayName = 'DataLinkEditor';
var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./packages/grafana-ui/src/components/DataLinks/DataLinkInput.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DataLinks/DataLinkInput.tsx ***!
  \************************************************************************/
/*! exports provided: DataLinkInput */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLinkInput", function() { return DataLinkInput; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _DataLinkSuggestions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DataLinkSuggestions */ "./packages/grafana-ui/src/components/DataLinks/DataLinkSuggestions.tsx");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../index */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _SelectionReference__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SelectionReference */ "./packages/grafana-ui/src/components/DataLinks/SelectionReference.ts");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var _grafana_slate_react__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/slate-react */ "./node_modules/@grafana/slate-react/lib/slate-react.es.js");
/* harmony import */ var slate_plain_serializer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! slate-plain-serializer */ "./node_modules/slate-plain-serializer/lib/slate-plain-serializer.es.js");
/* harmony import */ var react_popper__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! react-popper */ "./node_modules/react-popper/lib/esm/index.js");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _slate_plugins__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../slate-plugins */ "./packages/grafana-ui/src/slate-plugins/index.ts");
/* harmony import */ var _utils_slate__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../utils/slate */ "./packages/grafana-ui/src/utils/slate.ts");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");













var modulo = function (a, n) { return a - n * Math.floor(a / n); };
var plugins = [
    Object(_slate_plugins__WEBPACK_IMPORTED_MODULE_10__["SlatePrism"])({
        onlyIn: function (node) { return node.type === 'code_block'; },
        getSyntax: function () { return 'links'; },
    }),
];
var getStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_12__["stylesFactory"])(function (theme) { return ({
    editor: Object(emotion__WEBPACK_IMPORTED_MODULE_9__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    .token.builtInVariable {\n      color: ", ";\n    }\n    .token.variable {\n      color: ", ";\n    }\n  "], ["\n    .token.builtInVariable {\n      color: ", ";\n    }\n    .token.variable {\n      color: ", ";\n    }\n  "])), theme.colors.queryGreen, theme.colors.queryKeyword),
}); });
// This memoised also because rerendering the slate editor grabs focus which created problem in some cases this
// was used and changes to different state were propagated here.
var DataLinkInput = Object(react__WEBPACK_IMPORTED_MODULE_1__["memo"])(function (_a) {
    var value = _a.value, onChange = _a.onChange, suggestions = _a.suggestions;
    var editorRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["useRef"])();
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    var styles = getStyles(theme);
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(false), 2), showingSuggestions = _b[0], setShowingSuggestions = _b[1];
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(0), 2), suggestionsIndex = _c[0], setSuggestionsIndex = _c[1];
    var _d = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(Object(_index__WEBPACK_IMPORTED_MODULE_3__["makeValue"])(value)), 2), linkUrl = _d[0], setLinkUrl = _d[1];
    // Workaround for https://github.com/ianstormtaylor/slate/issues/2927
    var stateRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["useRef"])({ showingSuggestions: showingSuggestions, suggestions: suggestions, suggestionsIndex: suggestionsIndex, linkUrl: linkUrl, onChange: onChange });
    stateRef.current = { showingSuggestions: showingSuggestions, suggestions: suggestions, suggestionsIndex: suggestionsIndex, linkUrl: linkUrl, onChange: onChange };
    // SelectionReference is used to position the variables suggestion relatively to current DOM selection
    var selectionRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["useMemo"])(function () { return new _SelectionReference__WEBPACK_IMPORTED_MODULE_4__["SelectionReference"](); }, [setShowingSuggestions, linkUrl]);
    var onKeyDown = react__WEBPACK_IMPORTED_MODULE_1___default.a.useCallback(function (event, next) {
        if (!stateRef.current.showingSuggestions) {
            if (event.key === '=' || event.key === '$' || (event.keyCode === 32 && event.ctrlKey)) {
                return setShowingSuggestions(true);
            }
            return next();
        }
        switch (event.key) {
            case 'Backspace':
            case 'Escape':
                setShowingSuggestions(false);
                return setSuggestionsIndex(0);
            case 'Enter':
                event.preventDefault();
                return onVariableSelect(stateRef.current.suggestions[stateRef.current.suggestionsIndex]);
            case 'ArrowDown':
            case 'ArrowUp':
                event.preventDefault();
                var direction_1 = event.key === 'ArrowDown' ? 1 : -1;
                return setSuggestionsIndex(function (index) { return modulo(index + direction_1, stateRef.current.suggestions.length); });
            default:
                return next();
        }
    }, []);
    var onUrlChange = react__WEBPACK_IMPORTED_MODULE_1___default.a.useCallback(function (_a) {
        var value = _a.value;
        setLinkUrl(value);
    }, []);
    var onUrlBlur = react__WEBPACK_IMPORTED_MODULE_1___default.a.useCallback(function (event, editor, next) {
        // Callback needed for blur to work correctly
        stateRef.current.onChange(slate_plain_serializer__WEBPACK_IMPORTED_MODULE_7__["default"].serialize(stateRef.current.linkUrl), function () {
            // This needs to be called after state is updated.
            editorRef.current.blur();
        });
    }, []);
    var onVariableSelect = function (item, editor) {
        if (editor === void 0) { editor = editorRef.current; }
        var includeDollarSign = slate_plain_serializer__WEBPACK_IMPORTED_MODULE_7__["default"].serialize(editor.value).slice(-1) !== '$';
        if (item.origin !== _DataLinkSuggestions__WEBPACK_IMPORTED_MODULE_2__["VariableOrigin"].Template || item.value === _index__WEBPACK_IMPORTED_MODULE_3__["DataLinkBuiltInVars"].includeVars) {
            editor.insertText((includeDollarSign ? '$' : '') + "{" + item.value + "}");
        }
        else {
            editor.insertText("var-" + item.value + "=${" + item.value + "}");
        }
        setLinkUrl(editor.value);
        setShowingSuggestions(false);
        setSuggestionsIndex(0);
        onChange(slate_plain_serializer__WEBPACK_IMPORTED_MODULE_7__["default"].serialize(editor.value));
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_9__["cx"])('gf-form-input', Object(emotion__WEBPACK_IMPORTED_MODULE_9__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n          position: relative;\n          height: auto;\n        "], ["\n          position: relative;\n          height: auto;\n        "])))) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "slate-query-field" },
            showingSuggestions && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_5__["Portal"], null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_popper__WEBPACK_IMPORTED_MODULE_8__["Popper"], { referenceElement: selectionRef, placement: "top-end", modifiers: {
                        preventOverflow: { enabled: true, boundariesElement: 'window' },
                        arrow: { enabled: false },
                        offset: { offset: 250 },
                    } }, function (_a) {
                    var ref = _a.ref, style = _a.style, placement = _a.placement;
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: ref, style: style, "data-placement": placement },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DataLinkSuggestions__WEBPACK_IMPORTED_MODULE_2__["DataLinkSuggestions"], { suggestions: stateRef.current.suggestions, onSuggestionSelect: onVariableSelect, onClose: function () { return setShowingSuggestions(false); }, activeIndex: suggestionsIndex })));
                }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_slate_react__WEBPACK_IMPORTED_MODULE_6__["Editor"], { schema: _utils_slate__WEBPACK_IMPORTED_MODULE_11__["SCHEMA"], ref: editorRef, placeholder: "http://your-grafana.com/d/000000010/annotations", value: stateRef.current.linkUrl, onChange: onUrlChange, onBlur: onUrlBlur, onKeyDown: function (event, _editor, next) { return onKeyDown(event, next); }, plugins: plugins, className: styles.editor }))));
});
DataLinkInput.displayName = 'DataLinkInput';
var templateObject_1, templateObject_2;


/***/ }),

/***/ "./packages/grafana-ui/src/components/DataLinks/DataLinkSuggestions.tsx":
/*!******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DataLinks/DataLinkSuggestions.tsx ***!
  \******************************************************************************/
/*! exports provided: VariableOrigin, DataLinkSuggestions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VariableOrigin", function() { return VariableOrigin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLinkSuggestions", function() { return DataLinkSuggestions; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../index */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react-use/lib/useClickAway */ "./node_modules/react-use/lib/useClickAway.js");
/* harmony import */ var react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");









var VariableOrigin;
(function (VariableOrigin) {
    VariableOrigin["Series"] = "series";
    VariableOrigin["Field"] = "field";
    VariableOrigin["Value"] = "value";
    VariableOrigin["BuiltIn"] = "built-in";
    VariableOrigin["Template"] = "template";
})(VariableOrigin || (VariableOrigin = {}));
var getStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_8__["stylesFactory"])(function (theme) {
    var wrapperBg = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.dark2,
    }, theme.type);
    var wrapperShadow = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: theme.colors.gray5,
        dark: theme.colors.black,
    }, theme.type);
    var itemColor = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: theme.colors.black,
        dark: theme.colors.white,
    }, theme.type);
    var itemDocsColor = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: theme.colors.dark3,
        dark: theme.colors.gray2,
    }, theme.type);
    var itemBgHover = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: theme.colors.gray5,
        dark: theme.colors.dark7,
    }, theme.type);
    var itemBgActive = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: theme.colors.gray6,
        dark: theme.colors.dark9,
    }, theme.type);
    var separatorColor = Object(_index__WEBPACK_IMPORTED_MODULE_1__["selectThemeVariant"])({
        light: tinycolor2__WEBPACK_IMPORTED_MODULE_7___default()(wrapperBg.toString())
            .darken(10)
            .toString(),
        dark: tinycolor2__WEBPACK_IMPORTED_MODULE_7___default()(wrapperBg.toString())
            .lighten(10)
            .toString(),
    }, theme.type);
    return {
        list: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      border-bottom: 1px solid ", ";\n      &:last-child {\n        border: none;\n      }\n    "], ["\n      border-bottom: 1px solid ", ";\n      &:last-child {\n        border: none;\n      }\n    "])), separatorColor),
        wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      background: ", ";\n      z-index: 1;\n      width: 250px;\n      box-shadow: 0 5px 10px 0 ", ";\n    "], ["\n      background: ", ";\n      z-index: 1;\n      width: 250px;\n      box-shadow: 0 5px 10px 0 ", ";\n    "])), wrapperBg, wrapperShadow),
        item: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      background: none;\n      padding: 2px 8px;\n      color: ", ";\n      cursor: pointer;\n      &:hover {\n        background: ", ";\n      }\n    "], ["\n      background: none;\n      padding: 2px 8px;\n      color: ", ";\n      cursor: pointer;\n      &:hover {\n        background: ", ";\n      }\n    "])), itemColor, itemBgHover),
        label: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      color: ", ";\n    "], ["\n      color: ", ";\n    "])), theme.colors.textWeak),
        activeItem: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      background: ", ";\n      &:hover {\n        background: ", ";\n      }\n    "], ["\n      background: ", ";\n      &:hover {\n        background: ", ";\n      }\n    "])), itemBgActive, itemBgActive),
        itemValue: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      font-family: ", ";\n      font-size: ", ";\n    "], ["\n      font-family: ", ";\n      font-size: ", ";\n    "])), theme.typography.fontFamily.monospace, theme.typography.size.sm),
        itemDocs: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_7 || (templateObject_7 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      margin-top: ", ";\n      color: ", ";\n    "], ["\n      margin-top: ", ";\n      color: ", ";\n    "])), theme.spacing.xs, itemDocsColor),
    };
});
var DataLinkSuggestions = function (_a) {
    var suggestions = _a.suggestions, otherProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["suggestions"]);
    var ref = Object(react__WEBPACK_IMPORTED_MODULE_4__["useRef"])(null);
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_4__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_1__["ThemeContext"]);
    react_use_lib_useClickAway__WEBPACK_IMPORTED_MODULE_5___default()(ref, function () {
        if (otherProps.onClose) {
            otherProps.onClose();
        }
    });
    var groupedSuggestions = Object(react__WEBPACK_IMPORTED_MODULE_4__["useMemo"])(function () {
        return lodash__WEBPACK_IMPORTED_MODULE_3___default.a.groupBy(suggestions, function (s) { return s.origin; });
    }, [suggestions]);
    var styles = getStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", { ref: ref, className: styles.wrapper }, Object.keys(groupedSuggestions).map(function (key, i) {
        var indexOffset = i === 0
            ? 0
            : Object.keys(groupedSuggestions).reduce(function (acc, current, index) {
                if (index >= i) {
                    return acc;
                }
                return acc + groupedSuggestions[current].length;
            }, 0);
        return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(DataLinkSuggestionsList, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, otherProps, { suggestions: groupedSuggestions[key], label: "" + lodash__WEBPACK_IMPORTED_MODULE_3___default.a.capitalize(key), activeIndex: otherProps.activeIndex, activeIndexOffset: indexOffset, key: key })));
    })));
};
DataLinkSuggestions.displayName = 'DataLinkSuggestions';
var DataLinkSuggestionsList = react__WEBPACK_IMPORTED_MODULE_4___default.a.memo(function (_a) {
    var activeIndex = _a.activeIndex, activeIndexOffset = _a.activeIndexOffset, label = _a.label, onClose = _a.onClose, onSuggestionSelect = _a.onSuggestionSelect, suggestions = _a.suggestions;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_4__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_1__["ThemeContext"]);
    var styles = getStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_4___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_6__["List"], { className: styles.list, items: suggestions, renderItem: function (item, index) {
                return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(styles.item, index + activeIndexOffset === activeIndex && styles.activeItem), onClick: function () {
                        onSuggestionSelect(item);
                    }, title: item.documentation },
                    react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", { className: styles.itemValue },
                        react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", { className: styles.label }, label),
                        " ",
                        item.label)));
            } })));
});
DataLinkSuggestionsList.displayName = 'DataLinkSuggestionsList';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7;


/***/ }),

/***/ "./packages/grafana-ui/src/components/DataLinks/DataLinksContextMenu.tsx":
/*!*******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DataLinks/DataLinksContextMenu.tsx ***!
  \*******************************************************************************/
/*! exports provided: DataLinksContextMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLinksContextMenu", function() { return DataLinksContextMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _ContextMenu_WithContextMenu__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../ContextMenu/WithContextMenu */ "./packages/grafana-ui/src/components/ContextMenu/WithContextMenu.tsx");
/* harmony import */ var _utils_dataLinks__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/dataLinks */ "./packages/grafana-ui/src/utils/dataLinks.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");





var DataLinksContextMenu = function (_a) {
    var children = _a.children, links = _a.links;
    if (!links) {
        return children({});
    }
    var getDataLinksContextMenuItems = function () {
        return [{ items: Object(_utils_dataLinks__WEBPACK_IMPORTED_MODULE_3__["linkModelToContextMenuItems"])(links), label: 'Data links' }];
    };
    // Use this class name (exposed via render prop) to add context menu indicator to the click target of the visualization
    var targetClassName = Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    cursor: context-menu;\n  "], ["\n    cursor: context-menu;\n  "])));
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ContextMenu_WithContextMenu__WEBPACK_IMPORTED_MODULE_2__["WithContextMenu"], { getContextMenuItems: getDataLinksContextMenuItems }, function (_a) {
        var openMenu = _a.openMenu;
        return children({ openMenu: openMenu, targetClassName: targetClassName });
    }));
};
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/DataLinks/DataLinksEditor.tsx":
/*!**************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DataLinks/DataLinksEditor.tsx ***!
  \**************************************************************************/
/*! exports provided: DataLinksEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLinksEditor", function() { return DataLinksEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prismjs */ "./node_modules/prismjs/prism.js");
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prismjs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../index */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var _DataLinkEditor__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./DataLinkEditor */ "./packages/grafana-ui/src/components/DataLinks/DataLinkEditor.tsx");

// Libraries

// @ts-ignore

// Components




prismjs__WEBPACK_IMPORTED_MODULE_2___default.a.languages['links'] = {
    builtInVariable: {
        pattern: /(\${\S+?})/,
    },
};
var DataLinksEditor = react__WEBPACK_IMPORTED_MODULE_1___default.a.memo(function (_a) {
    var value = _a.value, onChange = _a.onChange, suggestions = _a.suggestions, maxLinks = _a.maxLinks;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var onAdd = function () {
        onChange(value ? tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](value, [{ url: '', title: '' }]) : [{ url: '', title: '' }]);
    };
    var onLinkChanged = function (linkIndex, newLink, callback) {
        onChange(value.map(function (item, listIndex) {
            if (linkIndex === listIndex) {
                return newLink;
            }
            return item;
        }), callback);
    };
    var onRemove = function (link) {
        onChange(value.filter(function (item) { return item !== link; }));
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        value && value.length > 0 && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n            margin-bottom: ", ";\n          "], ["\n            margin-bottom: ", ";\n          "])), theme.spacing.sm) }, value.map(function (link, index) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DataLinkEditor__WEBPACK_IMPORTED_MODULE_6__["DataLinkEditor"], { key: index.toString(), index: index, isLast: index === value.length - 1, value: link, onChange: onLinkChanged, onRemove: onRemove, suggestions: suggestions })); }))),
        (!value || (value && value.length < (maxLinks || Infinity))) && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_5__["Button"], { variant: "inverse", icon: "fa fa-plus", onClick: function () { return onAdd(); } }, "Add link"))));
});
DataLinksEditor.displayName = 'DataLinksEditor';
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/DataLinks/SelectionReference.ts":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DataLinks/SelectionReference.ts ***!
  \****************************************************************************/
/*! exports provided: SelectionReference */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionReference", function() { return SelectionReference; });
var SelectionReference = /** @class */ (function () {
    function SelectionReference() {
    }
    SelectionReference.prototype.getBoundingClientRect = function () {
        var selection = window.getSelection();
        var node = selection && selection.anchorNode;
        if (node && node.parentElement) {
            var rect = node.parentElement.getBoundingClientRect();
            return rect;
        }
        return {
            top: 0,
            left: 0,
            bottom: 0,
            right: 0,
            width: 0,
            height: 0,
        };
    };
    Object.defineProperty(SelectionReference.prototype, "clientWidth", {
        get: function () {
            return this.getBoundingClientRect().width;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(SelectionReference.prototype, "clientHeight", {
        get: function () {
            return this.getBoundingClientRect().height;
        },
        enumerable: true,
        configurable: true
    });
    return SelectionReference;
}());



/***/ }),

/***/ "./packages/grafana-ui/src/components/DeleteButton/DeleteButton.tsx":
/*!**************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/DeleteButton/DeleteButton.tsx ***!
  \**************************************************************************/
/*! exports provided: DeleteButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteButton", function() { return DeleteButton; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);


var DeleteButton = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DeleteButton, _super);
    function DeleteButton() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            showConfirm: false,
        };
        _this.onClickDelete = function (event) {
            if (event) {
                event.preventDefault();
            }
            _this.setState({
                showConfirm: true,
            });
        };
        _this.onClickCancel = function (event) {
            if (event) {
                event.preventDefault();
            }
            _this.setState({
                showConfirm: false,
            });
        };
        return _this;
    }
    DeleteButton.prototype.render = function () {
        var _a = this.props, onConfirm = _a.onConfirm, disabled = _a.disabled;
        var showConfirmClass = this.state.showConfirm ? 'show' : 'hide';
        var showDeleteButtonClass = this.state.showConfirm ? 'hide' : 'show';
        var disabledClass = disabled ? 'disabled btn-inverse' : '';
        var onClick = disabled ? function () { } : this.onClickDelete;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "delete-button-container" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "delete-button " + showDeleteButtonClass + " btn btn-danger btn-small " + disabledClass, onClick: onClick },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-remove" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "confirm-delete-container" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "confirm-delete " + showConfirmClass },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "btn btn-small", onClick: this.onClickCancel }, "Cancel"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "btn btn-danger btn-small", onClick: onConfirm }, "Confirm Delete")))));
    };
    return DeleteButton;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/EmptySearchResult/EmptySearchResult.tsx":
/*!************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/EmptySearchResult/EmptySearchResult.tsx ***!
  \************************************************************************************/
/*! exports provided: EmptySearchResult */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmptySearchResult", function() { return EmptySearchResult; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var EmptySearchResult = function (_a) {
    var children = _a.children;
    return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "empty-search-result" }, children);
};



/***/ }),

/***/ "./packages/grafana-ui/src/components/ErrorBoundary/ErrorBoundary.tsx":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ErrorBoundary/ErrorBoundary.tsx ***!
  \****************************************************************************/
/*! exports provided: ErrorBoundary, ErrorBoundaryAlert */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundary", function() { return ErrorBoundary; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundaryAlert", function() { return ErrorBoundaryAlert; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Alert_Alert__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Alert/Alert */ "./packages/grafana-ui/src/components/Alert/Alert.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");





var ErrorBoundary = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ErrorBoundary, _super);
    function ErrorBoundary() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            error: null,
            errorInfo: null,
        };
        return _this;
    }
    ErrorBoundary.prototype.componentDidCatch = function (error, errorInfo) {
        this.setState({
            error: error,
            errorInfo: errorInfo,
        });
    };
    ErrorBoundary.prototype.render = function () {
        var children = this.props.children;
        var _a = this.state, error = _a.error, errorInfo = _a.errorInfo;
        return children({
            error: error,
            errorInfo: errorInfo,
        });
    };
    return ErrorBoundary;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var getStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_4__["stylesFactory"])(function () {
    return Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    width: 500px;\n    margin: 64px auto;\n  "], ["\n    width: 500px;\n    margin: 64px auto;\n  "])));
});
var ErrorBoundaryAlert = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ErrorBoundaryAlert, _super);
    function ErrorBoundaryAlert() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ErrorBoundaryAlert.prototype.render = function () {
        var _a = this.props, title = _a.title, children = _a.children, style = _a.style;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ErrorBoundary, null, function (_a) {
            var error = _a.error, errorInfo = _a.errorInfo;
            if (!errorInfo) {
                return children;
            }
            if (style === 'alertbox') {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Alert_Alert__WEBPACK_IMPORTED_MODULE_2__["Alert"], { title: title || '' },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("details", { style: { whiteSpace: 'pre-wrap' } },
                        error && error.toString(),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                        errorInfo.componentStack)));
            }
            else {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: getStyles() },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h2", null, title),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("details", { style: { whiteSpace: 'pre-wrap' } },
                        error && error.toString(),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                        errorInfo.componentStack)));
            }
        }));
    };
    ErrorBoundaryAlert.defaultProps = {
        title: 'An unexpected error happened',
        style: 'alertbox',
    };
    return ErrorBoundaryAlert;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/FormField/FormField.tsx":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/FormField/FormField.tsx ***!
  \********************************************************************/
/*! exports provided: FormField */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormField", function() { return FormField; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../FormLabel/FormLabel */ "./packages/grafana-ui/src/components/FormLabel/FormLabel.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");




var defaultProps = {
    labelWidth: 6,
    inputWidth: 12,
};
/**
 * Default form field including label used in Grafana UI. Default input element is simple <input />. You can also pass
 * custom inputEl if required in which case inputWidth and inputProps are ignored.
 */
var FormField = function (_a) {
    var label = _a.label, tooltip = _a.tooltip, labelWidth = _a.labelWidth, inputWidth = _a.inputWidth, inputEl = _a.inputEl, className = _a.className, inputProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["label", "tooltip", "labelWidth", "inputWidth", "inputEl", "className"]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])('form-field', className) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth, tooltip: tooltip }, label),
        inputEl || (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ type: "text", className: "gf-form-input " + (inputWidth ? "width-" + inputWidth : '') }, inputProps)))));
};
FormField.displayName = 'FormField';
FormField.defaultProps = defaultProps;


/***/ }),

/***/ "./packages/grafana-ui/src/components/FormLabel/FormLabel.tsx":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/FormLabel/FormLabel.tsx ***!
  \********************************************************************/
/*! exports provided: FormLabel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormLabel", function() { return FormLabel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");




var FormLabel = function (_a) {
    var children = _a.children, isFocused = _a.isFocused, isInvalid = _a.isInvalid, className = _a.className, htmlFor = _a.htmlFor, tooltip = _a.tooltip, width = _a.width, rest = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["children", "isFocused", "isInvalid", "className", "htmlFor", "tooltip", "width"]);
    var classes = classnames__WEBPACK_IMPORTED_MODULE_2___default()("gf-form-label width-" + (width ? width : '10'), className, {
        'gf-form-label--is-focused': isFocused,
        'gf-form-label--is-invalid': isInvalid,
    });
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ className: classes }, rest, { htmlFor: htmlFor }),
        children,
        tooltip && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_3__["Tooltip"], { placement: "top", content: tooltip, theme: 'info' },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-help-icon gf-form-help-icon--right-normal" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-info-circle" }))))));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/Gauge/Gauge.tsx":
/*!************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Gauge/Gauge.tsx ***!
  \************************************************************/
/*! exports provided: Gauge */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gauge", function() { return Gauge; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./packages/grafana-ui/src/utils/index.ts");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");





var FONT_SCALE = 1;
var Gauge = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Gauge, _super);
    function Gauge() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.renderVisualization = function () {
            var _a = _this.props, width = _a.width, value = _a.value, height = _a.height, onClick = _a.onClick;
            var autoProps = calculateGaugeAutoProps(width, height, value.title);
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: { height: autoProps.gaugeHeight + "px", width: '100%' }, ref: function (element) { return (_this.canvasElement = element); }, onClick: onClick }),
                autoProps.showLabel && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                        textAlign: 'center',
                        fontSize: autoProps.titleFontSize,
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        position: 'relative',
                        width: '100%',
                        top: '-4px',
                        cursor: 'default',
                    } }, value.title))));
        };
        return _this;
    }
    Gauge.prototype.componentDidMount = function () {
        this.draw();
    };
    Gauge.prototype.componentDidUpdate = function () {
        this.draw();
    };
    Gauge.prototype.getFormattedThresholds = function () {
        var _a = this.props, maxValue = _a.maxValue, minValue = _a.minValue, thresholds = _a.thresholds, theme = _a.theme;
        var lastThreshold = thresholds[thresholds.length - 1];
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](thresholds.map(function (threshold, index) {
            if (index === 0) {
                return { value: minValue, color: Object(_utils__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(threshold.color, theme.type) };
            }
            var previousThreshold = thresholds[index - 1];
            return { value: threshold.value, color: Object(_utils__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(previousThreshold.color, theme.type) };
        }), [
            { value: maxValue, color: Object(_utils__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(lastThreshold.color, theme.type) },
        ]);
    };
    Gauge.prototype.getFontScale = function (length) {
        if (length > 12) {
            return FONT_SCALE - (length * 5) / 110;
        }
        return FONT_SCALE - (length * 5) / 101;
    };
    Gauge.prototype.draw = function () {
        var _a = this.props, maxValue = _a.maxValue, minValue = _a.minValue, showThresholdLabels = _a.showThresholdLabels, showThresholdMarkers = _a.showThresholdMarkers, width = _a.width, height = _a.height, theme = _a.theme, value = _a.value;
        var autoProps = calculateGaugeAutoProps(width, height, value.title);
        var dimension = Math.min(width, autoProps.gaugeHeight);
        var backgroundColor = Object(_themes__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
            dark: theme.colors.dark8,
            light: theme.colors.gray6,
        }, theme.type);
        var gaugeWidthReduceRatio = showThresholdLabels ? 1.5 : 1;
        var gaugeWidth = Math.min(dimension / 5.5, 40) / gaugeWidthReduceRatio;
        var thresholdMarkersWidth = gaugeWidth / 5;
        var fontSize = Math.min(dimension / 4, 100) * (value.text !== null ? this.getFontScale(value.text.length) : 1);
        var thresholdLabelFontSize = fontSize / 2.5;
        var options = {
            series: {
                gauges: {
                    gauge: {
                        min: minValue,
                        max: maxValue,
                        background: { color: backgroundColor },
                        border: { color: null },
                        shadow: { show: false },
                        width: gaugeWidth,
                    },
                    frame: { show: false },
                    label: { show: false },
                    layout: { margin: 0, thresholdWidth: 0, vMargin: 0 },
                    cell: { border: { width: 0 } },
                    threshold: {
                        values: this.getFormattedThresholds(),
                        label: {
                            show: showThresholdLabels,
                            margin: thresholdMarkersWidth + 1,
                            font: { size: thresholdLabelFontSize },
                        },
                        show: showThresholdMarkers,
                        width: thresholdMarkersWidth,
                    },
                    value: {
                        color: value.color,
                        formatter: function () {
                            return value.text;
                        },
                        font: { size: fontSize, family: theme.typography.fontFamily.sansSerif },
                    },
                    show: true,
                },
            },
        };
        var plotSeries = {
            data: [[0, value.numeric]],
            label: value.title,
        };
        try {
            jquery__WEBPACK_IMPORTED_MODULE_2___default.a.plot(this.canvasElement, [plotSeries], options);
        }
        catch (err) {
            console.log('Gauge rendering error', err, options, value);
        }
    };
    Gauge.prototype.render = function () {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: {
                width: '100%',
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                overflow: 'hidden',
            }, className: this.props.className }, this.renderVisualization()));
    };
    Gauge.defaultProps = {
        maxValue: 100,
        minValue: 0,
        showThresholdMarkers: true,
        showThresholdLabels: false,
        thresholds: [],
    };
    return Gauge;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

function calculateGaugeAutoProps(width, height, title) {
    var showLabel = title !== null && title !== undefined;
    var titleFontSize = Math.min((width * 0.15) / 1.5, 20); // 20% of height * line-height, max 40px
    var titleHeight = titleFontSize * 1.5;
    var availableHeight = showLabel ? height - titleHeight : height;
    var gaugeHeight = Math.min(availableHeight, width);
    return {
        showLabel: showLabel,
        gaugeHeight: gaugeHeight,
        titleFontSize: titleFontSize,
    };
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/Graph/Graph.tsx":
/*!************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Graph/Graph.tsx ***!
  \************************************************************/
/*! exports provided: Graph, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Graph", function() { return Graph; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_uniqBy__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/uniqBy */ "./node_modules/lodash/uniqBy.js");
/* harmony import */ var lodash_uniqBy__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_uniqBy__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libraries



// Types

var Graph = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Graph, _super);
    function Graph() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.element = null;
        _this.onPlotSelected = function (event, ranges) {
            var onHorizontalRegionSelected = _this.props.onHorizontalRegionSelected;
            if (onHorizontalRegionSelected) {
                onHorizontalRegionSelected(ranges.xaxis.from, ranges.xaxis.to);
            }
        };
        return _this;
    }
    Graph.prototype.componentDidUpdate = function () {
        this.draw();
    };
    Graph.prototype.componentDidMount = function () {
        this.draw();
        if (this.element) {
            this.$element = jquery__WEBPACK_IMPORTED_MODULE_1___default()(this.element);
            this.$element.bind('plotselected', this.onPlotSelected);
        }
    };
    Graph.prototype.componentWillUnmount = function () {
        this.$element.unbind('plotselected', this.onPlotSelected);
    };
    Graph.prototype.getYAxes = function (series) {
        if (series.length === 0) {
            return [{ show: true, min: -1, max: 1 }];
        }
        return lodash_uniqBy__WEBPACK_IMPORTED_MODULE_3___default()(series.map(function (s) {
            var index = s.yAxis ? s.yAxis.index : 1;
            var min = s.yAxis && !isNaN(s.yAxis.min) ? s.yAxis.min : null;
            var tickDecimals = s.yAxis && !isNaN(s.yAxis.tickDecimals) ? s.yAxis.tickDecimals : null;
            return {
                show: true,
                index: index,
                position: index === 1 ? 'left' : 'right',
                min: min,
                tickDecimals: tickDecimals,
            };
        }), function (yAxisConfig) { return yAxisConfig.index; });
    };
    Graph.prototype.draw = function () {
        if (this.element === null) {
            return;
        }
        var _a = this.props, width = _a.width, series = _a.series, timeRange = _a.timeRange, showLines = _a.showLines, showBars = _a.showBars, showPoints = _a.showPoints, isStacked = _a.isStacked, lineWidth = _a.lineWidth, timeZone = _a.timeZone, onHorizontalRegionSelected = _a.onHorizontalRegionSelected;
        if (!width) {
            return;
        }
        var ticks = width / 100;
        var min = timeRange.from.valueOf();
        var max = timeRange.to.valueOf();
        var yaxes = this.getYAxes(series);
        var flotOptions = {
            legend: {
                show: false,
            },
            series: {
                stack: isStacked,
                lines: {
                    show: showLines,
                    linewidth: lineWidth,
                    zero: false,
                },
                points: {
                    show: showPoints,
                    fill: 1,
                    fillColor: false,
                    radius: 2,
                },
                bars: {
                    show: showBars,
                    fill: 1,
                    barWidth: 1,
                    zero: false,
                    lineWidth: lineWidth,
                },
                shadowSize: 0,
            },
            xaxis: {
                show: true,
                mode: 'time',
                min: min,
                max: max,
                label: 'Datetime',
                ticks: ticks,
                timeformat: timeFormat(ticks, min, max),
                timezone: timeZone ? timeZone : _grafana_data__WEBPACK_IMPORTED_MODULE_4__["DefaultTimeZone"],
            },
            yaxes: yaxes,
            grid: {
                minBorderMargin: 0,
                markings: [],
                backgroundColor: null,
                borderWidth: 0,
                // hoverable: true,
                clickable: true,
                color: '#a1a1a1',
                margin: { left: 0, right: 0 },
                labelMarginX: 0,
            },
            selection: {
                mode: onHorizontalRegionSelected ? 'x' : null,
                color: '#666',
            },
        };
        try {
            jquery__WEBPACK_IMPORTED_MODULE_1___default.a.plot(this.element, series, flotOptions);
        }
        catch (err) {
            console.log('Graph rendering error', err, flotOptions, series);
            throw new Error('Error rendering panel');
        }
    };
    Graph.prototype.render = function () {
        var _this = this;
        var _a = this.props, height = _a.height, series = _a.series;
        var noDataToBeDisplayed = series.length === 0;
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "graph-panel" },
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "graph-panel__chart", ref: function (e) { return (_this.element = e); }, style: { height: height } }),
            noDataToBeDisplayed && react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "datapoints-warning" }, "No data")));
    };
    Graph.defaultProps = {
        showLines: true,
        showPoints: false,
        showBars: false,
        isStacked: false,
        lineWidth: 1,
    };
    return Graph;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));

// Copied from graph.ts
function timeFormat(ticks, min, max) {
    if (min && max && ticks) {
        var range = max - min;
        var secPerTick = range / ticks / 1000;
        var oneDay = 86400000;
        var oneYear = 31536000000;
        if (secPerTick <= 45) {
            return '%H:%M:%S';
        }
        if (secPerTick <= 7200 || range <= oneDay) {
            return '%H:%M';
        }
        if (secPerTick <= 80000) {
            return '%m/%d %H:%M';
        }
        if (secPerTick <= 2419200 || range <= oneYear) {
            return '%m/%d';
        }
        return '%Y-%m';
    }
    return '%H:%M';
}
/* harmony default export */ __webpack_exports__["default"] = (Graph);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Graph/GraphLegend.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Graph/GraphLegend.tsx ***!
  \******************************************************************/
/*! exports provided: GraphLegend */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphLegend", function() { return GraphLegend; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Legend_Legend__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Legend/Legend */ "./packages/grafana-ui/src/components/Legend/Legend.tsx");
/* harmony import */ var _GraphLegendItem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./GraphLegendItem */ "./packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx");
/* harmony import */ var _Legend_LegendTable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Legend/LegendTable */ "./packages/grafana-ui/src/components/Legend/LegendTable.tsx");
/* harmony import */ var _Legend_LegendList__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Legend/LegendList */ "./packages/grafana-ui/src/components/Legend/LegendList.tsx");
/* harmony import */ var lodash_union__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lodash/union */ "./node_modules/lodash/union.js");
/* harmony import */ var lodash_union__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(lodash_union__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash/sortBy */ "./node_modules/lodash/sortBy.js");
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash_sortBy__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_index__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../themes/index */ "./packages/grafana-ui/src/themes/index.ts");











var GraphLegend = function (_a) {
    var items = _a.items, displayMode = _a.displayMode, sortKey = _a.sortBy, sortDesc = _a.sortDesc, onToggleSort = _a.onToggleSort, onSeriesAxisToggle = _a.onSeriesAxisToggle, placement = _a.placement, className = _a.className, graphLegendItemProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["items", "displayMode", "sortBy", "sortDesc", "onToggleSort", "onSeriesAxisToggle", "placement", "className"]);
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_8__["ThemeContext"]);
    if (displayMode === _Legend_Legend__WEBPACK_IMPORTED_MODULE_2__["LegendDisplayMode"].Table) {
        var columns = items
            .map(function (item) {
            if (item.displayValues) {
                return item.displayValues.map(function (i) { return i.title; });
            }
            return [];
        })
            .reduce(function (acc, current) {
            return lodash_union__WEBPACK_IMPORTED_MODULE_6___default()(acc, current.filter(function (item) { return !!item; }));
        }, ['']);
        var sortedItems = sortKey
            ? lodash_sortBy__WEBPACK_IMPORTED_MODULE_7___default()(items, function (item) {
                if (item.displayValues) {
                    var stat = item.displayValues.filter(function (stat) { return stat.title === sortKey; })[0];
                    return stat && stat.numeric;
                }
                return undefined;
            })
            : items;
        var legendTableEvenRowBackground_1 = Object(_themes_index__WEBPACK_IMPORTED_MODULE_10__["selectThemeVariant"])({
            dark: theme.colors.dark6,
            light: theme.colors.gray5,
        }, theme.type);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Legend_LegendTable__WEBPACK_IMPORTED_MODULE_4__["LegendTable"], { className: Object(emotion__WEBPACK_IMPORTED_MODULE_9__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n          font-size: ", ";\n          th {\n            padding: ", " ", ";\n          }\n        "], ["\n          font-size: ", ";\n          th {\n            padding: ", " ", ";\n          }\n        "])), theme.typography.size.sm, theme.spacing.xxs, theme.spacing.sm), items: sortDesc ? sortedItems.reverse() : sortedItems, columns: columns, placement: placement, sortBy: sortKey, sortDesc: sortDesc, itemRenderer: function (item, index) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_GraphLegendItem__WEBPACK_IMPORTED_MODULE_3__["GraphLegendTableRow"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ key: item.label + "-" + index, item: item, onToggleAxis: function () {
                    if (onSeriesAxisToggle) {
                        onSeriesAxisToggle(item.label, item.yAxis === 1 ? 2 : 1);
                    }
                }, className: Object(emotion__WEBPACK_IMPORTED_MODULE_9__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n              background: ", ";\n            "], ["\n              background: ", ";\n            "])), index % 2 === 0 ? legendTableEvenRowBackground_1 : 'none') }, graphLegendItemProps))); }, onToggleSort: onToggleSort }));
    }
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Legend_LegendList__WEBPACK_IMPORTED_MODULE_5__["LegendList"], { items: items, placement: placement, itemRenderer: function (item) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_GraphLegendItem__WEBPACK_IMPORTED_MODULE_3__["GraphLegendListItem"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ item: item, onToggleAxis: function () {
                if (onSeriesAxisToggle) {
                    onSeriesAxisToggle(item.label, item.yAxis === 1 ? 2 : 1);
                }
            } }, graphLegendItemProps))); } }));
};
GraphLegend.displayName = 'GraphLegend';
var templateObject_1, templateObject_2;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx ***!
  \**********************************************************************/
/*! exports provided: GraphLegendListItem, GraphLegendTableRow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphLegendListItem", function() { return GraphLegendListItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphLegendTableRow", function() { return GraphLegendTableRow; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _Legend_LegendSeriesIcon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Legend/LegendSeriesIcon */ "./packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx");
/* harmony import */ var _Legend_LegendStatsList__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Legend/LegendStatsList */ "./packages/grafana-ui/src/components/Legend/LegendStatsList.tsx");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");







var GraphLegendListItem = function (_a) {
    var item = _a.item, onSeriesColorChange = _a.onSeriesColorChange, onToggleAxis = _a.onToggleAxis, onLabelClick = _a.onLabelClick;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__["ThemeContext"]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Legend_LegendSeriesIcon__WEBPACK_IMPORTED_MODULE_3__["LegendSeriesIcon"], { disabled: !onSeriesColorChange, color: item.color, onColorChange: function (color) {
                if (onSeriesColorChange) {
                    onSeriesColorChange(item.label, color);
                }
            }, onToggleAxis: onToggleAxis, yAxis: item.yAxis }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { onClick: function (event) {
                if (onLabelClick) {
                    onLabelClick(item, event);
                }
            }, className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n          cursor: pointer;\n          white-space: pre-wrap;\n          color: ", ";\n        "], ["\n          cursor: pointer;\n          white-space: pre-wrap;\n          color: ", ";\n        "])), !item.isVisible && theme.colors.linkDisabled) }, item.label),
        item.displayValues && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Legend_LegendStatsList__WEBPACK_IMPORTED_MODULE_4__["LegendStatsList"], { stats: item.displayValues })));
};
var getStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_6__["stylesFactory"])(function (theme) {
    return {
        row: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      font-size: ", ";\n      td {\n        padding: ", " ", ";\n        white-space: nowrap;\n      }\n    "], ["\n      font-size: ", ";\n      td {\n        padding: ", " ", ";\n        white-space: nowrap;\n      }\n    "])), theme.typography.size.sm, theme.spacing.xxs, theme.spacing.sm),
        label: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      cursor: pointer;\n      white-space: nowrap;\n    "], ["\n      cursor: pointer;\n      white-space: nowrap;\n    "]))),
        itemWrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      display: flex;\n      white-space: nowrap;\n    "], ["\n      display: flex;\n      white-space: nowrap;\n    "]))),
        value: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      text-align: right;\n    "], ["\n      text-align: right;\n    "]))),
        yAxisLabel: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      color: ", ";\n    "], ["\n      color: ", ";\n    "])), theme.colors.gray2),
    };
});
var GraphLegendTableRow = function (_a) {
    var item = _a.item, onSeriesColorChange = _a.onSeriesColorChange, onToggleAxis = _a.onToggleAxis, onLabelClick = _a.onLabelClick, className = _a.className;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__["ThemeContext"]);
    var styles = getStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(styles.row, className) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: styles.itemWrapper },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Legend_LegendSeriesIcon__WEBPACK_IMPORTED_MODULE_3__["LegendSeriesIcon"], { disabled: !!onSeriesColorChange, color: item.color, onColorChange: function (color) {
                        if (onSeriesColorChange) {
                            onSeriesColorChange(item.label, color);
                        }
                    }, onToggleAxis: onToggleAxis, yAxis: item.yAxis }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { onClick: function (event) {
                        if (onLabelClick) {
                            onLabelClick(item, event);
                        }
                    }, className: styles.label },
                    item.label,
                    " ",
                    item.yAxis === 2 && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: styles.yAxisLabel }, "(right y-axis)")))),
        item.displayValues &&
            item.displayValues.map(function (stat, index) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { className: styles.value, key: stat.title + "-" + index }, stat.text));
            })));
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Graph/GraphSeriesToggler.tsx":
/*!*************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Graph/GraphSeriesToggler.tsx ***!
  \*************************************************************************/
/*! exports provided: GraphSeriesToggler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphSeriesToggler", function() { return GraphSeriesToggler; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_difference__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/difference */ "./node_modules/lodash/difference.js");
/* harmony import */ var lodash_difference__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_difference__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_isEqual__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/isEqual */ "./node_modules/lodash/isEqual.js");
/* harmony import */ var lodash_isEqual__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_isEqual__WEBPACK_IMPORTED_MODULE_3__);




var GraphSeriesToggler = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GraphSeriesToggler, _super);
    function GraphSeriesToggler(props) {
        var _this = _super.call(this, props) || this;
        _this.onSeriesToggle = _this.onSeriesToggle.bind(_this);
        _this.state = {
            hiddenSeries: [],
            toggledSeries: props.series,
        };
        return _this;
    }
    GraphSeriesToggler.prototype.componentDidUpdate = function (prevProps) {
        var series = this.props.series;
        if (!lodash_isEqual__WEBPACK_IMPORTED_MODULE_3___default()(prevProps.series, series)) {
            this.setState({ hiddenSeries: [], toggledSeries: series });
        }
    };
    GraphSeriesToggler.prototype.onSeriesToggle = function (label, event) {
        var _a = this.props, series = _a.series, onHiddenSeriesChanged = _a.onHiddenSeriesChanged;
        var hiddenSeries = this.state.hiddenSeries;
        if (event.ctrlKey || event.metaKey || event.shiftKey) {
            // Toggling series with key makes the series itself to toggle
            var newHiddenSeries_1 = hiddenSeries.indexOf(label) > -1
                ? hiddenSeries.filter(function (series) { return series !== label; })
                : hiddenSeries.concat([label]);
            var toggledSeries_1 = series.map(function (series) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { isVisible: newHiddenSeries_1.indexOf(series.label) === -1 })); });
            this.setState({ hiddenSeries: newHiddenSeries_1, toggledSeries: toggledSeries_1 }, function () {
                return onHiddenSeriesChanged ? onHiddenSeriesChanged(newHiddenSeries_1) : undefined;
            });
            return;
        }
        // Toggling series with out key toggles all the series but the clicked one
        var allSeriesLabels = series.map(function (series) { return series.label; });
        var newHiddenSeries = hiddenSeries.length + 1 === allSeriesLabels.length ? [] : lodash_difference__WEBPACK_IMPORTED_MODULE_2___default()(allSeriesLabels, [label]);
        var toggledSeries = series.map(function (series) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { isVisible: newHiddenSeries.indexOf(series.label) === -1 })); });
        this.setState({ hiddenSeries: newHiddenSeries, toggledSeries: toggledSeries }, function () {
            return onHiddenSeriesChanged ? onHiddenSeriesChanged(newHiddenSeries) : undefined;
        });
    };
    GraphSeriesToggler.prototype.render = function () {
        var children = this.props.children;
        var toggledSeries = this.state.toggledSeries;
        return children({
            onSeriesToggle: this.onSeriesToggle,
            toggledSeries: toggledSeries,
        });
    };
    return GraphSeriesToggler;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Graph/GraphWithLegend.tsx":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Graph/GraphWithLegend.tsx ***!
  \**********************************************************************/
/*! exports provided: GraphWithLegend */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphWithLegend", function() { return GraphWithLegend; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _Graph__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Graph */ "./packages/grafana-ui/src/components/Graph/Graph.tsx");
/* harmony import */ var _GraphLegend__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./GraphLegend */ "./packages/grafana-ui/src/components/Graph/GraphLegend.tsx");
/* harmony import */ var _CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../CustomScrollbar/CustomScrollbar */ "./packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");
// Libraries







var getGraphWithLegendStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_6__["stylesFactory"])(function (_a) {
    var placement = _a.placement;
    return ({
        wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: flex;\n    flex-direction: ", ";\n    height: 100%;\n  "], ["\n    display: flex;\n    flex-direction: ", ";\n    height: 100%;\n  "])), placement === 'under' ? 'column' : 'row'),
        graphContainer: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    min-height: 65%;\n    flex-grow: 1;\n  "], ["\n    min-height: 65%;\n    flex-grow: 1;\n  "]))),
        legendContainer: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    padding: 10px 0;\n    max-height: ", ";\n  "], ["\n    padding: 10px 0;\n    max-height: ", ";\n  "])), placement === 'under' ? '35%' : 'none'),
    });
});
var shouldHideLegendItem = function (data, hideEmpty, hideZero) {
    if (hideEmpty === void 0) { hideEmpty = false; }
    if (hideZero === void 0) { hideZero = false; }
    var isZeroOnlySeries = data.reduce(function (acc, current) { return acc + (current[1] || 0); }, 0) === 0;
    var isNullOnlySeries = !data.reduce(function (acc, current) { return acc && current[1] !== null; }, true);
    return (hideEmpty && isNullOnlySeries) || (hideZero && isZeroOnlySeries);
};
var GraphWithLegend = function (props) {
    var series = props.series, timeRange = props.timeRange, width = props.width, height = props.height, showBars = props.showBars, showLines = props.showLines, showPoints = props.showPoints, sortLegendBy = props.sortLegendBy, sortLegendDesc = props.sortLegendDesc, isLegendVisible = props.isLegendVisible, displayMode = props.displayMode, placement = props.placement, onSeriesAxisToggle = props.onSeriesAxisToggle, onSeriesColorChange = props.onSeriesColorChange, onSeriesToggle = props.onSeriesToggle, onToggleSort = props.onToggleSort, hideEmpty = props.hideEmpty, hideZero = props.hideZero, isStacked = props.isStacked, lineWidth = props.lineWidth, onHorizontalRegionSelected = props.onHorizontalRegionSelected, timeZone = props.timeZone;
    var _a = getGraphWithLegendStyles(props), graphContainer = _a.graphContainer, wrapper = _a.wrapper, legendContainer = _a.legendContainer;
    var legendItems = series.reduce(function (acc, s) {
        return shouldHideLegendItem(s.data, hideEmpty, hideZero)
            ? acc
            : acc.concat([
                {
                    label: s.label,
                    color: s.color,
                    isVisible: s.isVisible,
                    yAxis: s.yAxis.index,
                    displayValues: s.info || [],
                },
            ]);
    }, []);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: wrapper },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: graphContainer },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Graph__WEBPACK_IMPORTED_MODULE_3__["Graph"], { series: series.filter(function (s) { return !!s.isVisible; }), timeRange: timeRange, timeZone: timeZone, showLines: showLines, showPoints: showPoints, showBars: showBars, width: width, height: height, key: isLegendVisible ? 'legend-visible' : 'legend-invisible', isStacked: isStacked, lineWidth: lineWidth, onHorizontalRegionSelected: onHorizontalRegionSelected })),
        isLegendVisible && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: legendContainer },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_5__["CustomScrollbar"], { hideHorizontalTrack: true },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_GraphLegend__WEBPACK_IMPORTED_MODULE_4__["GraphLegend"], { items: legendItems, displayMode: displayMode, placement: placement, sortBy: sortLegendBy, sortDesc: sortLegendDesc, onLabelClick: function (item, event) {
                        if (onSeriesToggle) {
                            onSeriesToggle(item.label, event);
                        }
                    }, onSeriesColorChange: onSeriesColorChange, onSeriesAxisToggle: onSeriesAxisToggle, onToggleSort: onToggleSort }))))));
};
var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Input/Input.tsx":
/*!************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Input/Input.tsx ***!
  \************************************************************/
/*! exports provided: InputStatus, Input */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputStatus", function() { return InputStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Input", function() { return Input; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./packages/grafana-ui/src/utils/index.ts");




var InputStatus;
(function (InputStatus) {
    InputStatus["Invalid"] = "invalid";
    InputStatus["Valid"] = "valid";
})(InputStatus || (InputStatus = {}));
var Input = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Input, _super);
    function Input() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            error: null,
        };
        _this.validatorAsync = function (validationRules) {
            return function (evt) {
                var errors = Object(_utils__WEBPACK_IMPORTED_MODULE_3__["validate"])(evt.target.value, validationRules);
                _this.setState(function (prevState) {
                    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, prevState, { error: errors ? errors[0] : null });
                });
            };
        };
        _this.populateEventPropsWithStatus = function (restProps, validationEvents) {
            var inputElementProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, restProps);
            if (!validationEvents) {
                return inputElementProps;
            }
            Object.keys(_utils__WEBPACK_IMPORTED_MODULE_3__["EventsWithValidation"]).forEach(function (eventName) {
                if (Object(_utils__WEBPACK_IMPORTED_MODULE_3__["hasValidationEvent"])(eventName, validationEvents) || restProps[eventName]) {
                    inputElementProps[eventName] = function (evt) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
                        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    evt.persist(); // Needed for async. https://reactjs.org/docs/events.html#event-pooling
                                    if (!Object(_utils__WEBPACK_IMPORTED_MODULE_3__["hasValidationEvent"])(eventName, validationEvents)) return [3 /*break*/, 2];
                                    return [4 /*yield*/, this.validatorAsync(validationEvents[eventName]).apply(this, [evt])];
                                case 1:
                                    _a.sent();
                                    _a.label = 2;
                                case 2:
                                    if (restProps[eventName]) {
                                        restProps[eventName].apply(null, [evt, this.status]);
                                    }
                                    return [2 /*return*/];
                            }
                        });
                    }); };
                }
            });
            return inputElementProps;
        };
        return _this;
    }
    Object.defineProperty(Input.prototype, "status", {
        get: function () {
            return this.state.error ? InputStatus.Invalid : InputStatus.Valid;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Input.prototype, "isInvalid", {
        get: function () {
            return this.status === InputStatus.Invalid;
        },
        enumerable: true,
        configurable: true
    });
    Input.prototype.render = function () {
        var _a = this.props, validationEvents = _a.validationEvents, className = _a.className, hideErrorMessage = _a.hideErrorMessage, restProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["validationEvents", "className", "hideErrorMessage"]);
        var error = this.state.error;
        var inputClassName = classnames__WEBPACK_IMPORTED_MODULE_2___default()('gf-form-input', { invalid: this.isInvalid }, className);
        var inputElementProps = this.populateEventPropsWithStatus(restProps, validationEvents);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: { flexGrow: 1 } },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, inputElementProps, { className: inputClassName })),
            error && !hideErrorMessage && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, error)));
    };
    Input.defaultProps = {
        className: '',
    };
    return Input;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/JSONFormatter/JSONFormatter.tsx":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/JSONFormatter/JSONFormatter.tsx ***!
  \****************************************************************************/
/*! exports provided: JSONFormatter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONFormatter", function() { return JSONFormatter; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _json_explorer_json_explorer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./json_explorer/json_explorer */ "./packages/grafana-ui/src/components/JSONFormatter/json_explorer/json_explorer.ts");


 // We have made some monkey-patching of json-formatter-js so we can't switch right now
var JSONFormatter = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](JSONFormatter, _super);
    function JSONFormatter() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.wrapperRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["createRef"])();
        _this.renderJson = function () {
            var _a = _this.props, json = _a.json, config = _a.config, open = _a.open, onDidRender = _a.onDidRender;
            var wrapperEl = _this.wrapperRef.current;
            var formatter = new _json_explorer_json_explorer__WEBPACK_IMPORTED_MODULE_2__["JsonExplorer"](json, open, config);
            // @ts-ignore
            var hasChildren = wrapperEl.hasChildNodes();
            if (hasChildren) {
                // @ts-ignore
                wrapperEl.replaceChild(formatter.render(), wrapperEl.lastChild);
            }
            else {
                // @ts-ignore
                wrapperEl.appendChild(formatter.render());
            }
            if (onDidRender) {
                onDidRender(formatter.json);
            }
        };
        return _this;
    }
    JSONFormatter.prototype.componentDidMount = function () {
        this.renderJson();
    };
    JSONFormatter.prototype.componentDidUpdate = function () {
        this.renderJson();
    };
    JSONFormatter.prototype.render = function () {
        var className = this.props.className;
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: className, ref: this.wrapperRef });
    };
    JSONFormatter.defaultProps = {
        open: 3,
        config: {
            animateOpen: true,
        },
    };
    return JSONFormatter;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts":
/*!***********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts ***!
  \***********************************************************************************/
/*! exports provided: isObject, getObjectName, getType, getValuePreview, getPreview, cssClass, createElement */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getObjectName", function() { return getObjectName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getType", function() { return getType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValuePreview", function() { return getValuePreview; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPreview", function() { return getPreview; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cssClass", function() { return cssClass; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createElement", function() { return createElement; });
// Based on work https://github.com/mohsen1/json-formatter-js
// License MIT, Copyright (c) 2015 Mohsen Azimi
/*
 * Escapes `"` characters from string
 */
function escapeString(str) {
    return str.replace('"', '"');
}
/*
 * Determines if a value is an object
 */
function isObject(value) {
    var type = typeof value;
    return !!value && type === 'object';
}
/*
 * Gets constructor name of an object.
 * From http://stackoverflow.com/a/332429
 *
 */
function getObjectName(object) {
    if (object === undefined) {
        return '';
    }
    if (object === null) {
        return 'Object';
    }
    if (typeof object === 'object' && !object.constructor) {
        return 'Object';
    }
    var funcNameRegex = /function ([^(]*)/;
    var results = funcNameRegex.exec(object.constructor.toString());
    if (results && results.length > 1) {
        return results[1];
    }
    else {
        return '';
    }
}
/*
 * Gets type of an object. Returns "null" for null objects
 */
function getType(object) {
    if (object === null) {
        return 'null';
    }
    return typeof object;
}
/*
 * Generates inline preview for a JavaScript object based on a value
 */
function getValuePreview(object, value) {
    var type = getType(object);
    if (type === 'null' || type === 'undefined') {
        return type;
    }
    if (type === 'string') {
        value = '"' + escapeString(value) + '"';
    }
    if (type === 'function') {
        // Remove content of the function
        return (object
            .toString()
            .replace(/[\r\n]/g, '')
            .replace(/\{.*\}/, '') + '{…}');
    }
    return value;
}
/*
 * Generates inline preview for a JavaScript object
 */
var value = '';
function getPreview(obj) {
    if (isObject(obj)) {
        value = getObjectName(obj);
        if (Array.isArray(obj)) {
            value += '[' + obj.length + ']';
        }
    }
    else {
        value = getValuePreview(obj, obj.toString());
    }
    return value;
}
/*
 * Generates a prefixed CSS class name
 */
function cssClass(className) {
    return "json-formatter-" + className;
}
/*
 * Creates a new DOM element with given type and class
 * TODO: move me to helpers
 */
function createElement(type, className, content) {
    var el = document.createElement(type);
    if (className) {
        el.classList.add(cssClass(className));
    }
    if (content !== undefined) {
        if (content instanceof Node) {
            el.appendChild(content);
        }
        else {
            el.appendChild(document.createTextNode(String(content)));
        }
    }
    return el;
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/JSONFormatter/json_explorer/json_explorer.ts":
/*!*****************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/JSONFormatter/json_explorer/json_explorer.ts ***!
  \*****************************************************************************************/
/*! exports provided: JsonExplorer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JsonExplorer", function() { return JsonExplorer; });
/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers */ "./packages/grafana-ui/src/components/JSONFormatter/json_explorer/helpers.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
// Based on work https://github.com/mohsen1/json-formatter-js
// License MIT, Copyright (c) 2015 Mohsen Azimi


var DATE_STRING_REGEX = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/;
var PARTIAL_DATE_REGEX = /\d{2}:\d{2}:\d{2} GMT-\d{4}/;
var JSON_DATE_REGEX = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/;
// When toggleing, don't animated removal or addition of more than a few items
var MAX_ANIMATED_TOGGLE_ITEMS = 10;
var requestAnimationFrame = window.requestAnimationFrame ||
    (function (cb) {
        cb();
        return 0;
    });
var _defaultConfig = {
    animateOpen: true,
    animateClose: true,
};
/**
 * @class JsonExplorer
 *
 * JsonExplorer allows you to render JSON objects in HTML with a
 * **collapsible** navigation.
 */
var JsonExplorer = /** @class */ (function () {
    /**
     * @param {object} json The JSON object you want to render. It has to be an
     * object or array. Do NOT pass raw JSON string.
     *
     * @param {number} [open=1] his number indicates up to how many levels the
     * rendered tree should expand. Set it to `0` to make the whole tree collapsed
     * or set it to `Infinity` to expand the tree deeply
     *
     * @param {object} [config=defaultConfig] -
     *  defaultConfig = {
     *   hoverPreviewEnabled: false,
     *   hoverPreviewArrayCount: 100,
     *   hoverPreviewFieldCount: 5
     * }
     *
     * Available configurations:
     *  #####Hover Preview
     * * `hoverPreviewEnabled`:  enable preview on hover
     * * `hoverPreviewArrayCount`: number of array items to show in preview Any
     *    array larger than this number will be shown as `Array[XXX]` where `XXX`
     *    is length of the array.
     * * `hoverPreviewFieldCount`: number of object properties to show for object
     *   preview. Any object with more properties that thin number will be
     *   truncated.
     *
     * @param {string} [key=undefined] The key that this object in it's parent
     * context
     */
    function JsonExplorer(json, open, config, key) {
        if (open === void 0) { open = 1; }
        if (config === void 0) { config = _defaultConfig; }
        this.json = json;
        this.open = open;
        this.config = config;
        this.key = key;
        // Hold the open state after the toggler is used
        this._isOpen = null;
        // A reference to the element that we render to
        this.element = null;
        this.skipChildren = false;
    }
    Object.defineProperty(JsonExplorer.prototype, "isOpen", {
        /*
         * is formatter open?
         */
        get: function () {
            if (this._isOpen !== null) {
                return this._isOpen;
            }
            else {
                return this.open > 0;
            }
        },
        /*
         * set open state (from toggler)
         */
        set: function (value) {
            this._isOpen = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "isDate", {
        /*
         * is this a date string?
         */
        get: function () {
            return (this.type === 'string' &&
                (DATE_STRING_REGEX.test(this.json) || JSON_DATE_REGEX.test(this.json) || PARTIAL_DATE_REGEX.test(this.json)));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "isUrl", {
        /*
         * is this a URL string?
         */
        get: function () {
            return this.type === 'string' && this.json.indexOf('http') === 0;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "isArray", {
        /*
         * is this an array?
         */
        get: function () {
            return Array.isArray(this.json);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "isObject", {
        /*
         * is this an object?
         * Note: In this context arrays are object as well
         */
        get: function () {
            return Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(this.json);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "isEmptyObject", {
        /*
         * is this an empty object with no properties?
         */
        get: function () {
            return !this.keys.length && !this.isArray;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "isEmpty", {
        /*
         * is this an empty object or array?
         */
        get: function () {
            return this.isEmptyObject || (this.keys && !this.keys.length && this.isArray);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "hasKey", {
        /*
         * did we receive a key argument?
         * This means that the formatter was called as a sub formatter of a parent formatter
         */
        get: function () {
            return typeof this.key !== 'undefined';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "constructorName", {
        /*
         * if this is an object, get constructor function name
         */
        get: function () {
            return Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getObjectName"])(this.json);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "type", {
        /*
         * get type of this value
         * Possible values: all JavaScript primitive types plus "array" and "null"
         */
        get: function () {
            return Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getType"])(this.json);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(JsonExplorer.prototype, "keys", {
        /*
         * get object keys
         * If there is an empty key we pad it wit quotes to make it visible
         */
        get: function () {
            if (this.isObject) {
                return Object.keys(this.json).map(function (key) { return (key ? key : '""'); });
            }
            else {
                return [];
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Toggles `isOpen` state
     *
     */
    JsonExplorer.prototype.toggleOpen = function () {
        this.isOpen = !this.isOpen;
        if (this.element) {
            if (this.isOpen) {
                this.appendChildren(this.config.animateOpen);
            }
            else {
                this.removeChildren(this.config.animateClose);
            }
            this.element.classList.toggle(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('open'));
        }
    };
    /**
     * Open all children up to a certain depth.
     * Allows actions such as expand all/collapse all
     *
     */
    JsonExplorer.prototype.openAtDepth = function (depth) {
        if (depth === void 0) { depth = 1; }
        if (depth < 0) {
            return;
        }
        this.open = depth;
        this.isOpen = depth !== 0;
        if (this.element) {
            this.removeChildren(false);
            if (depth === 0) {
                this.element.classList.remove(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('open'));
            }
            else {
                this.appendChildren(this.config.animateOpen);
                this.element.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('open'));
            }
        }
    };
    JsonExplorer.prototype.isNumberArray = function () {
        return this.json.length > 0 && this.json.length < 4 && (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(this.json[0]) || lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(this.json[1]));
    };
    JsonExplorer.prototype.renderArray = function () {
        var arrayWrapperSpan = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span');
        arrayWrapperSpan.appendChild(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'bracket', '['));
        // some pretty handling of number arrays
        if (this.isNumberArray()) {
            this.json.forEach(function (val, index) {
                if (index > 0) {
                    arrayWrapperSpan.appendChild(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'array-comma', ','));
                }
                arrayWrapperSpan.appendChild(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'number', val));
            });
            this.skipChildren = true;
        }
        else {
            arrayWrapperSpan.appendChild(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'number', this.json.length));
        }
        arrayWrapperSpan.appendChild(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'bracket', ']'));
        return arrayWrapperSpan;
    };
    /**
     * Renders an HTML element and installs event listeners
     *
     * @returns {HTMLDivElement}
     */
    JsonExplorer.prototype.render = function (skipRoot) {
        if (skipRoot === void 0) { skipRoot = false; }
        // construct the root element and assign it to this.element
        this.element = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('div', 'row');
        // construct the toggler link
        var togglerLink = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('a', 'toggler-link');
        var togglerIcon = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'toggler');
        // if this is an object we need a wrapper span (toggler)
        if (this.isObject) {
            togglerLink.appendChild(togglerIcon);
        }
        // if this is child of a parent formatter we need to append the key
        if (this.hasKey) {
            togglerLink.appendChild(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'key', this.key + ":"));
        }
        // Value for objects and arrays
        if (this.isObject) {
            // construct the value holder element
            var value = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'value');
            // we need a wrapper span for objects
            var objectWrapperSpan = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span');
            // get constructor name and append it to wrapper span
            var constructorName = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span', 'constructor-name', this.constructorName);
            objectWrapperSpan.appendChild(constructorName);
            // if it's an array append the array specific elements like brackets and length
            if (this.isArray) {
                var arrayWrapperSpan = this.renderArray();
                objectWrapperSpan.appendChild(arrayWrapperSpan);
            }
            // append object wrapper span to toggler link
            value.appendChild(objectWrapperSpan);
            togglerLink.appendChild(value);
            // Primitive values
        }
        else {
            // make a value holder element
            var value = this.isUrl ? Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('a') : Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('span');
            // add type and other type related CSS classes
            value.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])(this.type));
            if (this.isDate) {
                value.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('date'));
            }
            if (this.isUrl) {
                value.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('url'));
                value.setAttribute('href', this.json);
            }
            // Append value content to value element
            var valuePreview = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getValuePreview"])(this.json, this.json);
            value.appendChild(document.createTextNode(valuePreview));
            // append the value element to toggler link
            togglerLink.appendChild(value);
        }
        // construct a children element
        var children = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["createElement"])('div', 'children');
        // set CSS classes for children
        if (this.isObject) {
            children.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('object'));
        }
        if (this.isArray) {
            children.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('array'));
        }
        if (this.isEmpty) {
            children.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('empty'));
        }
        // set CSS classes for root element
        if (this.config && this.config.theme) {
            this.element.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])(this.config.theme));
        }
        if (this.isOpen) {
            this.element.classList.add(Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('open'));
        }
        // append toggler and children elements to root element
        if (!skipRoot) {
            this.element.appendChild(togglerLink);
        }
        if (!this.skipChildren) {
            this.element.appendChild(children);
        }
        else {
            // remove togglerIcon
            togglerLink.removeChild(togglerIcon);
        }
        // if formatter is set to be open call appendChildren
        if (this.isObject && this.isOpen) {
            this.appendChildren();
        }
        // add event listener for toggling
        if (this.isObject) {
            togglerLink.addEventListener('click', this.toggleOpen.bind(this));
        }
        return this.element;
    };
    /**
     * Appends all the children to children element
     * Animated option is used when user triggers this via a click
     */
    JsonExplorer.prototype.appendChildren = function (animated) {
        var _this = this;
        if (animated === void 0) { animated = false; }
        var children = this.element && this.element.querySelector("div." + Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('children'));
        if (!children || this.isEmpty) {
            return;
        }
        if (animated) {
            var index_1 = 0;
            var addAChild_1 = function () {
                var key = _this.keys[index_1];
                var formatter = new JsonExplorer(_this.json[key], _this.open - 1, _this.config, key);
                children.appendChild(formatter.render());
                index_1 += 1;
                if (index_1 < _this.keys.length) {
                    if (index_1 > MAX_ANIMATED_TOGGLE_ITEMS) {
                        addAChild_1();
                    }
                    else {
                        requestAnimationFrame(addAChild_1);
                    }
                }
            };
            requestAnimationFrame(addAChild_1);
        }
        else {
            this.keys.forEach(function (key) {
                var formatter = new JsonExplorer(_this.json[key], _this.open - 1, _this.config, key);
                children.appendChild(formatter.render());
            });
        }
    };
    /**
     * Removes all the children from children element
     * Animated option is used when user triggers this via a click
     */
    JsonExplorer.prototype.removeChildren = function (animated) {
        if (animated === void 0) { animated = false; }
        var childrenElement = this.element && this.element.querySelector("div." + Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cssClass"])('children'));
        if (animated) {
            var childrenRemoved_1 = 0;
            var removeAChild_1 = function () {
                if (childrenElement && childrenElement.children.length) {
                    childrenElement.removeChild(childrenElement.children[0]);
                    childrenRemoved_1 += 1;
                    if (childrenRemoved_1 > MAX_ANIMATED_TOGGLE_ITEMS) {
                        removeAChild_1();
                    }
                    else {
                        requestAnimationFrame(removeAChild_1);
                    }
                }
            };
            requestAnimationFrame(removeAChild_1);
        }
        else {
            if (childrenElement) {
                childrenElement.innerHTML = '';
            }
        }
    };
    return JsonExplorer;
}());



/***/ }),

/***/ "./packages/grafana-ui/src/components/Legend/Legend.tsx":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Legend/Legend.tsx ***!
  \**************************************************************/
/*! exports provided: LegendDisplayMode, LegendList, LegendTable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LegendDisplayMode", function() { return LegendDisplayMode; });
/* harmony import */ var _LegendList__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./LegendList */ "./packages/grafana-ui/src/components/Legend/LegendList.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendList", function() { return _LegendList__WEBPACK_IMPORTED_MODULE_0__["LegendList"]; });

/* harmony import */ var _LegendTable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./LegendTable */ "./packages/grafana-ui/src/components/Legend/LegendTable.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendTable", function() { return _LegendTable__WEBPACK_IMPORTED_MODULE_1__["LegendTable"]; });



var LegendDisplayMode;
(function (LegendDisplayMode) {
    LegendDisplayMode["List"] = "list";
    LegendDisplayMode["Table"] = "table";
})(LegendDisplayMode || (LegendDisplayMode = {}));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Legend/LegendList.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Legend/LegendList.tsx ***!
  \******************************************************************/
/*! exports provided: LegendList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LegendList", function() { return LegendList; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _List_InlineList__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../List/InlineList */ "./packages/grafana-ui/src/components/List/InlineList.tsx");
/* harmony import */ var _List_List__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../List/List */ "./packages/grafana-ui/src/components/List/List.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");







var getStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_6__["stylesFactory"])(function (theme) { return ({
    item: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    padding-left: 10px;\n    display: flex;\n    font-size: ", ";\n    white-space: nowrap;\n  "], ["\n    padding-left: 10px;\n    display: flex;\n    font-size: ", ";\n    white-space: nowrap;\n  "])), theme.typography.size.sm),
    wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: flex;\n    flex-wrap: wrap;\n    justify-content: space-between;\n    width: 100%;\n  "], ["\n    display: flex;\n    flex-wrap: wrap;\n    justify-content: space-between;\n    width: 100%;\n  "]))),
    section: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: flex;\n  "], ["\n    display: flex;\n  "]))),
    sectionRight: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    justify-content: flex-end;\n    flex-grow: 1;\n  "], ["\n    justify-content: flex-end;\n    flex-grow: 1;\n  "]))),
}); });
var LegendList = function (_a) {
    var items = _a.items, itemRenderer = _a.itemRenderer, placement = _a.placement, className = _a.className;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__["ThemeContext"]);
    var styles = getStyles(theme);
    var renderItem = function (item, index) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: styles.item }, itemRenderer ? itemRenderer(item, index) : item.label);
    };
    var getItemKey = function (item) { return "" + item.label; };
    return placement === 'under' ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["cx"])(styles.wrapper, className) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.section },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_List_InlineList__WEBPACK_IMPORTED_MODULE_2__["InlineList"], { items: items.filter(function (item) { return item.yAxis === 1; }), renderItem: renderItem, getItemKey: getItemKey })),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["cx"])(styles.section, styles.sectionRight) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_List_InlineList__WEBPACK_IMPORTED_MODULE_2__["InlineList"], { items: items.filter(function (item) { return item.yAxis !== 1; }), renderItem: renderItem, getItemKey: getItemKey })))) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_List_List__WEBPACK_IMPORTED_MODULE_3__["List"], { items: items, renderItem: renderItem, getItemKey: getItemKey, className: className }));
};
LegendList.displayName = 'LegendList';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx ***!
  \************************************************************************/
/*! exports provided: LegendSeriesIcon */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LegendSeriesIcon", function() { return LegendSeriesIcon; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../ColorPicker/ColorPicker */ "./packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx");
/* harmony import */ var _SeriesIcon__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SeriesIcon */ "./packages/grafana-ui/src/components/Legend/SeriesIcon.tsx");





var LegendSeriesIcon = function (_a) {
    var disabled = _a.disabled, yAxis = _a.yAxis, color = _a.color, onColorChange = _a.onColorChange, onToggleAxis = _a.onToggleAxis;
    var iconProps = {
        color: color,
    };
    if (!disabled) {
        iconProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, iconProps, { className: 'pointer' });
    }
    return disabled ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])('graph-legend-icon', disabled && Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n            cursor: default;\n          "], ["\n            cursor: default;\n          "])))) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_SeriesIcon__WEBPACK_IMPORTED_MODULE_4__["SeriesIcon"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, iconProps)))) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_3__["SeriesColorPicker"], { yaxis: yAxis, color: color, onChange: onColorChange, onToggleAxis: onToggleAxis, enableNamedColors: true }, function (_a) {
        var ref = _a.ref, showColorPicker = _a.showColorPicker, hideColorPicker = _a.hideColorPicker;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { ref: ref, onClick: showColorPicker, onMouseLeave: hideColorPicker, className: "graph-legend-icon" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_SeriesIcon__WEBPACK_IMPORTED_MODULE_4__["SeriesIcon"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, iconProps))));
    }));
};
LegendSeriesIcon.displayName = 'LegendSeriesIcon';
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Legend/LegendStatsList.tsx":
/*!***********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Legend/LegendStatsList.tsx ***!
  \***********************************************************************/
/*! exports provided: LegendStatsList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LegendStatsList", function() { return LegendStatsList; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _List_InlineList__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../List/InlineList */ "./packages/grafana-ui/src/components/List/InlineList.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var lodash_capitalize__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash/capitalize */ "./node_modules/lodash/capitalize.js");
/* harmony import */ var lodash_capitalize__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash_capitalize__WEBPACK_IMPORTED_MODULE_4__);





var LegendItemStat = function (_a) {
    var stat = _a.stat;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n        margin-left: 6px;\n      "], ["\n        margin-left: 6px;\n      "]))) },
        stat.title && lodash_capitalize__WEBPACK_IMPORTED_MODULE_4___default()(stat.title) + ":",
        " ",
        stat.text));
};
LegendItemStat.displayName = 'LegendItemStat';
var LegendStatsList = function (_a) {
    var stats = _a.stats;
    if (stats.length === 0) {
        return null;
    }
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_List_InlineList__WEBPACK_IMPORTED_MODULE_2__["InlineList"], { items: stats, renderItem: function (stat) { return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LegendItemStat, { stat: stat }); } });
};
LegendStatsList.displayName = 'LegendStatsList';
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Legend/LegendTable.tsx":
/*!*******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Legend/LegendTable.tsx ***!
  \*******************************************************************/
/*! exports provided: LegendTable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LegendTable", function() { return LegendTable; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");




var LegendTable = function (_a) {
    var items = _a.items, columns = _a.columns, sortBy = _a.sortBy, sortDesc = _a.sortDesc, itemRenderer = _a.itemRenderer, className = _a.className, onToggleSort = _a.onToggleSort;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("table", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n          width: 100%;\n          td {\n            padding: 2px 10px;\n          }\n        "], ["\n          width: 100%;\n          td {\n            padding: 2px 10px;\n          }\n        "]))), className) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("thead", null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null, columns.map(function (columnHeader) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", { key: columnHeader, className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                  color: ", ";\n                  font-weight: bold;\n                  text-align: right;\n                  cursor: pointer;\n                "], ["\n                  color: ", ";\n                  font-weight: bold;\n                  text-align: right;\n                  cursor: pointer;\n                "])), theme.colors.blue), onClick: function () {
                        if (onToggleSort) {
                            onToggleSort(columnHeader);
                        }
                    } },
                    columnHeader,
                    sortBy === columnHeader && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])("fa fa-caret-" + (sortDesc ? 'down' : 'up'), Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                        margin-left: ", ";\n                      "], ["\n                        margin-left: ", ";\n                      "])), theme.spacing.sm)) }))));
            }))),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tbody", null, items.map(function (item, index) {
            return itemRenderer ? (itemRenderer(item, index)) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { key: item.label + "-" + index },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, item.label)));
        }))));
};
var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Legend/SeriesIcon.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Legend/SeriesIcon.tsx ***!
  \******************************************************************/
/*! exports provided: SeriesIcon */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SeriesIcon", function() { return SeriesIcon; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");


var SeriesIcon = function (_a) {
    var color = _a.color, className = _a.className;
    return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["cx"])('fa', 'fa-minus', className), style: { color: color } });
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/List/AbstractList.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/List/AbstractList.tsx ***!
  \******************************************************************/
/*! exports provided: AbstractList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbstractList", function() { return AbstractList; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");




var getStyles = Object(_themes__WEBPACK_IMPORTED_MODULE_3__["stylesFactory"])(function (inlineList) {
    if (inlineList === void 0) { inlineList = false; }
    return ({
        list: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    list-style-type: none;\n    margin: 0;\n    padding: 0;\n  "], ["\n    list-style-type: none;\n    margin: 0;\n    padding: 0;\n  "]))),
        item: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: ", ";\n  "], ["\n    display: ", ";\n  "])), (inlineList && 'inline-block') || 'block'),
    });
});
var AbstractList = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AbstractList, _super);
    function AbstractList(props) {
        return _super.call(this, props) || this;
    }
    AbstractList.prototype.render = function () {
        var _a = this.props, items = _a.items, renderItem = _a.renderItem, getItemKey = _a.getItemKey, className = _a.className, inline = _a.inline;
        var styles = getStyles(inline);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(styles.list, className) }, items.map(function (item, i) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: styles.item, key: getItemKey ? getItemKey(item) : i }, renderItem(item, i)));
        })));
    };
    return AbstractList;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));

var templateObject_1, templateObject_2;


/***/ }),

/***/ "./packages/grafana-ui/src/components/List/InlineList.tsx":
/*!****************************************************************!*\
  !*** ./packages/grafana-ui/src/components/List/InlineList.tsx ***!
  \****************************************************************/
/*! exports provided: InlineList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InlineList", function() { return InlineList; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _AbstractList__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AbstractList */ "./packages/grafana-ui/src/components/List/AbstractList.tsx");



var InlineList = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InlineList, _super);
    function InlineList() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    InlineList.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AbstractList__WEBPACK_IMPORTED_MODULE_2__["AbstractList"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ inline: true }, this.props));
    };
    return InlineList;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));



/***/ }),

/***/ "./packages/grafana-ui/src/components/List/List.tsx":
/*!**********************************************************!*\
  !*** ./packages/grafana-ui/src/components/List/List.tsx ***!
  \**********************************************************/
/*! exports provided: List */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "List", function() { return List; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _AbstractList__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AbstractList */ "./packages/grafana-ui/src/components/List/AbstractList.tsx");



var List = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](List, _super);
    function List() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    List.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AbstractList__WEBPACK_IMPORTED_MODULE_2__["AbstractList"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.props));
    };
    return List;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));



/***/ }),

/***/ "./packages/grafana-ui/src/components/LoadingPlaceholder/LoadingPlaceholder.tsx":
/*!**************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/LoadingPlaceholder/LoadingPlaceholder.tsx ***!
  \**************************************************************************************/
/*! exports provided: LoadingPlaceholder */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadingPlaceholder", function() { return LoadingPlaceholder; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var LoadingPlaceholder = function (_a) {
    var text = _a.text;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
        text,
        " ",
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-spinner fa-spin" })));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogLabel.tsx":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogLabel.tsx ***!
  \**************************************************************/
/*! exports provided: LogLabel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLabel", function() { return LogLabel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _LogLabelStats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LogLabelStats */ "./packages/grafana-ui/src/components/Logs/LogLabelStats.tsx");
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");







var getStyles = function (theme) {
    return {
        logsLabel: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-label;\n      display: flex;\n      padding: 0 2px;\n      background-color: ", ";\n      border-radius: ", ";\n      margin: 0 4px 2px 0;\n      text-overflow: ellipsis;\n      white-space: nowrap;\n      overflow: hidden;\n    "], ["\n      label: logs-label;\n      display: flex;\n      padding: 0 2px;\n      background-color: ", ";\n      border-radius: ", ";\n      margin: 0 4px 2px 0;\n      text-overflow: ellipsis;\n      white-space: nowrap;\n      overflow: hidden;\n    "])), Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_5__["selectThemeVariant"])({ light: theme.colors.gray5, dark: theme.colors.dark6 }, theme.type), theme.border.radius),
        logsLabelValue: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-label__value;\n      display: inline-block;\n      max-width: 20em;\n      text-overflow: ellipsis;\n      overflow: hidden;\n    "], ["\n      label: logs-label__value;\n      display: inline-block;\n      max-width: 20em;\n      text-overflow: ellipsis;\n      overflow: hidden;\n    "]))),
        logsLabelIcon: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-label__icon;\n      border-left: solid 1px ", ";\n      padding: 0 2px;\n      cursor: pointer;\n      margin-left: 2px;\n    "], ["\n      label: logs-label__icon;\n      border-left: solid 1px ", ";\n      padding: 0 2px;\n      cursor: pointer;\n      margin-left: 2px;\n    "])), Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_5__["selectThemeVariant"])({ light: theme.colors.gray5, dark: theme.colors.dark1 }, theme.type)),
        logsLabelStats: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      position: absolute;\n      top: 1.25em;\n      left: -10px;\n      z-index: 100;\n      justify-content: space-between;\n      box-shadow: 0 0 20px ", ";\n    "], ["\n      position: absolute;\n      top: 1.25em;\n      left: -10px;\n      z-index: 100;\n      justify-content: space-between;\n      box-shadow: 0 0 20px ", ";\n    "])), Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_5__["selectThemeVariant"])({ light: theme.colors.white, dark: theme.colors.black }, theme.type)),
    };
};
var UnThemedLogLabel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UnThemedLogLabel, _super);
    function UnThemedLogLabel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            stats: [],
            showStats: false,
        };
        _this.onClickClose = function () {
            _this.setState({ showStats: false });
        };
        _this.onClickLabel = function () {
            var _a = _this.props, onClickLabel = _a.onClickLabel, label = _a.label, value = _a.value;
            if (onClickLabel) {
                onClickLabel(label, value);
            }
        };
        _this.onClickStats = function () {
            _this.setState(function (state) {
                if (state.showStats) {
                    return { showStats: false, stats: [] };
                }
                var allRows = _this.props.getRows();
                var stats = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["calculateLogsLabelStats"])(allRows, _this.props.label);
                return { showStats: true, stats: stats };
            });
        };
        return _this;
    }
    UnThemedLogLabel.prototype.render = function () {
        var _a = this.props, getRows = _a.getRows, label = _a.label, plain = _a.plain, value = _a.value, theme = _a.theme;
        var styles = getStyles(theme);
        var _b = this.state, showStats = _b.showStats, stats = _b.stats;
        var tooltip = label + ": " + value;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.logsLabel]) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.logsLabelValue]), title: tooltip }, value),
            !plain && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { title: "Filter for label", onClick: this.onClickLabel, className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.logsLabelIcon, 'fa fa-search-plus']) })),
            !plain && getRows && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { onClick: this.onClickStats, className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.logsLabelIcon, 'fa fa-signal']) })),
            showStats && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.logsLabelStats]) },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabelStats__WEBPACK_IMPORTED_MODULE_4__["LogLabelStats"], { stats: stats, rowCount: getRows().length, label: label, value: value, onClickClose: this.onClickClose })))));
    };
    return UnThemedLogLabel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
var LogLabel = Object(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_6__["withTheme"])(UnThemedLogLabel);
LogLabel.displayName = 'LogLabel';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogLabelStats.tsx":
/*!*******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogLabelStats.tsx ***!
  \*******************************************************************/
/*! exports provided: LogLabelStats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLabelStats", function() { return LogLabelStats; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _LogLabelStatsRow__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LogLabelStatsRow */ "./packages/grafana-ui/src/components/Logs/LogLabelStatsRow.tsx");
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony import */ var _themes_index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/index */ "./packages/grafana-ui/src/themes/index.ts");






var STATS_ROW_LIMIT = 5;
var getStyles = function (theme) { return ({
    logsStats: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats;\n    background-color: ", ";\n    color: ", ";\n    border: 1px solid ", ";\n    border-radius: ", ";\n    max-width: 500px;\n  "], ["\n    label: logs-stats;\n    background-color: ", ";\n    color: ", ";\n    border: 1px solid ", ";\n    border-radius: ", ";\n    max-width: 500px;\n  "])), Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({ light: theme.colors.pageBg, dark: theme.colors.dark2 }, theme.type), theme.colors.text, Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({ light: theme.colors.gray5, dark: theme.colors.dark9 }, theme.type), theme.border.radius.md),
    logsStatsHeader: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats__header;\n    background: ", ";\n    padding: 6px 10px;\n    display: flex;\n  "], ["\n    label: logs-stats__header;\n    background: ", ";\n    padding: 6px 10px;\n    display: flex;\n  "])), Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({ light: theme.colors.gray5, dark: theme.colors.dark9 }, theme.type)),
    logsStatsTitle: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats__title;\n    font-weight: ", ";\n    padding-right: ", ";\n    overflow: hidden;\n    display: inline-block;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    flex-grow: 1;\n  "], ["\n    label: logs-stats__title;\n    font-weight: ", ";\n    padding-right: ", ";\n    overflow: hidden;\n    display: inline-block;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    flex-grow: 1;\n  "])), theme.typography.weight.semibold, theme.spacing.d),
    logsStatsClose: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats__close;\n    cursor: pointer;\n  "], ["\n    label: logs-stats__close;\n    cursor: pointer;\n  "]))),
    logsStatsBody: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats__body;\n    padding: 20px 10px 10px 10px;\n  "], ["\n    label: logs-stats__body;\n    padding: 20px 10px 10px 10px;\n  "]))),
}); };
var UnThemedLogLabelStats = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UnThemedLogLabelStats, _super);
    function UnThemedLogLabelStats() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    UnThemedLogLabelStats.prototype.render = function () {
        var _a = this.props, label = _a.label, rowCount = _a.rowCount, stats = _a.stats, value = _a.value, onClickClose = _a.onClickClose, theme = _a.theme;
        var style = getStyles(theme);
        var topRows = stats.slice(0, STATS_ROW_LIMIT);
        var activeRow = topRows.find(function (row) { return row.value === value; });
        var otherRows = stats.slice(STATS_ROW_LIMIT);
        var insertActiveRow = !activeRow;
        // Remove active row from other to show extra
        if (insertActiveRow) {
            activeRow = otherRows.find(function (row) { return row.value === value; });
            otherRows = otherRows.filter(function (row) { return row.value !== value; });
        }
        var otherCount = otherRows.reduce(function (sum, row) { return sum + row.count; }, 0);
        var topCount = topRows.reduce(function (sum, row) { return sum + row.count; }, 0);
        var total = topCount + otherCount;
        var otherProportion = otherCount / total;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStats]) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsHeader]) },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsTitle]) },
                    label,
                    ": ",
                    total,
                    " of ",
                    rowCount,
                    " rows have that label"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsClose, 'fa fa-remove']), onClick: onClickClose })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsBody]) },
                topRows.map(function (stat) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabelStatsRow__WEBPACK_IMPORTED_MODULE_3__["LogLabelStatsRow"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ key: stat.value }, stat, { active: stat.value === value }))); }),
                insertActiveRow && activeRow && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabelStatsRow__WEBPACK_IMPORTED_MODULE_3__["LogLabelStatsRow"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ key: activeRow.value }, activeRow, { active: true })),
                otherCount > 0 && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabelStatsRow__WEBPACK_IMPORTED_MODULE_3__["LogLabelStatsRow"], { key: "__OTHERS__", count: otherCount, value: "Other", proportion: otherProportion })))));
    };
    return UnThemedLogLabelStats;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
var LogLabelStats = Object(_themes_index__WEBPACK_IMPORTED_MODULE_5__["withTheme"])(UnThemedLogLabelStats);
LogLabelStats.displayName = 'LogLabelStats';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogLabelStatsRow.tsx":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogLabelStatsRow.tsx ***!
  \**********************************************************************/
/*! exports provided: LogLabelStatsRow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLabelStatsRow", function() { return LogLabelStatsRow; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");




var getStyles = function (theme) { return ({
    logsStatsRow: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row;\n    margin: ", "px 0;\n  "], ["\n    label: logs-stats-row;\n    margin: ", "px 0;\n  "])), parseInt(theme.spacing.d, 10) / 1.75),
    logsStatsRowActive: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row--active;\n    color: ", ";\n    position: relative;\n\n    ::after {\n      display: inline;\n      content: '*';\n      position: absolute;\n      top: 0;\n      left: -8px;\n    }\n  "], ["\n    label: logs-stats-row--active;\n    color: ", ";\n    position: relative;\n\n    ::after {\n      display: inline;\n      content: '*';\n      position: absolute;\n      top: 0;\n      left: -8px;\n    }\n  "])), theme.colors.blue),
    logsStatsRowLabel: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row__label;\n    display: flex;\n    margin-bottom: 1px;\n  "], ["\n    label: logs-stats-row__label;\n    display: flex;\n    margin-bottom: 1px;\n  "]))),
    logsStatsRowValue: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row__value;\n    flex: 1;\n    text-overflow: ellipsis;\n    overflow: hidden;\n  "], ["\n    label: logs-stats-row__value;\n    flex: 1;\n    text-overflow: ellipsis;\n    overflow: hidden;\n  "]))),
    logsStatsRowCount: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row__count;\n    text-align: right;\n    margin-left: 0.5em;\n  "], ["\n    label: logs-stats-row__count;\n    text-align: right;\n    margin-left: 0.5em;\n  "]))),
    logsStatsRowPercent: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row__percent;\n    text-align: right;\n    margin-left: 0.5em;\n    width: 3em;\n  "], ["\n    label: logs-stats-row__percent;\n    text-align: right;\n    margin-left: 0.5em;\n    width: 3em;\n  "]))),
    logsStatsRowBar: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_7 || (templateObject_7 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row__bar;\n    height: 4px;\n    overflow: hidden;\n    background: ", ";\n  "], ["\n    label: logs-stats-row__bar;\n    height: 4px;\n    overflow: hidden;\n    background: ", ";\n  "])), theme.colors.textFaint),
    logsStatsRowInnerBar: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_8 || (templateObject_8 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: logs-stats-row__innerbar;\n    height: 4px;\n    overflow: hidden;\n    background: ", ";\n    background: ", ";\n  "], ["\n    label: logs-stats-row__innerbar;\n    height: 4px;\n    overflow: hidden;\n    background: ", ";\n    background: ", ";\n  "])), theme.colors.textFaint, theme.colors.blue),
}); };
var LogLabelStatsRow = function (_a) {
    var active = _a.active, count = _a.count, proportion = _a.proportion, value = _a.value;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    var style = getStyles(theme);
    var percent = Math.round(proportion * 100) + "%";
    var barStyle = { width: percent };
    var className = active ? Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRow, style.logsStatsRowActive]) : Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRow]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: className },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRowLabel]) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRowValue]), title: value }, value),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRowCount]) }, count),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRowPercent]) }, percent)),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRowBar]) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([style.logsStatsRowInnerBar]), style: barStyle }))));
};
LogLabelStatsRow.displayName = 'LogLabelStatsRow';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogLabels.tsx":
/*!***************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogLabels.tsx ***!
  \***************************************************************/
/*! exports provided: LogLabels */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLabels", function() { return LogLabels; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _LogLabel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LogLabel */ "./packages/grafana-ui/src/components/Logs/LogLabel.tsx");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");





var getStyles = function (theme) { return ({
    logsLabels: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: flex;\n    flex-wrap: wrap;\n  "], ["\n    display: flex;\n    flex-wrap: wrap;\n  "]))),
}); };
var LogLabels = function (_a) {
    var getRows = _a.getRows, labels = _a.labels, onClickLabel = _a.onClickLabel, plain = _a.plain;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var styles = getStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.logsLabels]) }, Object.keys(labels).map(function (key) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabel__WEBPACK_IMPORTED_MODULE_3__["LogLabel"], { key: key, getRows: getRows, label: key, value: labels[key], plain: plain, onClickLabel: onClickLabel })); })));
};
LogLabels.displayName = 'LogLabels';
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogMessageAnsi.tsx":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogMessageAnsi.tsx ***!
  \********************************************************************/
/*! exports provided: LogMessageAnsi */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogMessageAnsi", function() { return LogMessageAnsi; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_ansicolor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/ansicolor */ "./packages/grafana-ui/src/utils/ansicolor.ts");



function convertCSSToStyle(css) {
    return css.split(/;\s*/).reduce(function (accumulated, line) {
        var match = line.match(/([^:\s]+)\s*:\s*(.+)/);
        if (match && match[1] && match[2]) {
            var key = match[1].replace(/-(a-z)/g, function (_, character) { return character.toUpperCase(); });
            // @ts-ignore
            accumulated[key] = match[2];
        }
        return accumulated;
    }, {});
}
var LogMessageAnsi = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LogMessageAnsi, _super);
    function LogMessageAnsi() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            chunks: [],
            prevValue: '',
        };
        return _this;
    }
    LogMessageAnsi.getDerivedStateFromProps = function (props, state) {
        if (props.value === state.prevValue) {
            return null;
        }
        var parsed = _utils_ansicolor__WEBPACK_IMPORTED_MODULE_2__["default"].parse(props.value);
        return {
            chunks: parsed.spans.map(function (span) {
                return span.css
                    ? {
                        style: convertCSSToStyle(span.css),
                        text: span.text,
                    }
                    : { text: span.text };
            }),
            prevValue: props.value,
        };
    };
    LogMessageAnsi.prototype.render = function () {
        var chunks = this.state.chunks;
        return chunks.map(function (chunk, index) {
            return chunk.style ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: index, style: chunk.style }, chunk.text)) : (chunk.text);
        });
    };
    return LogMessageAnsi;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogRow.tsx":
/*!************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogRow.tsx ***!
  \************************************************************/
/*! exports provided: LogRow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogRow", function() { return LogRow; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_highlight_words__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-highlight-words */ "./node_modules/react-highlight-words/dist/main.js");
/* harmony import */ var react_highlight_words__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_highlight_words__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../index */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _LogRowContextProvider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./LogRowContextProvider */ "./packages/grafana-ui/src/components/Logs/LogRowContextProvider.tsx");
/* harmony import */ var _LogRowContext__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./LogRowContext */ "./packages/grafana-ui/src/components/Logs/LogRowContext.tsx");
/* harmony import */ var _LogLabels__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./LogLabels */ "./packages/grafana-ui/src/components/Logs/LogLabels.tsx");
/* harmony import */ var _LogMessageAnsi__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./LogMessageAnsi */ "./packages/grafana-ui/src/components/Logs/LogMessageAnsi.tsx");
/* harmony import */ var _LogLabelStats__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./LogLabelStats */ "./packages/grafana-ui/src/components/Logs/LogLabelStats.tsx");
/* harmony import */ var _themes_index__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../themes/index */ "./packages/grafana-ui/src/themes/index.ts");
/* harmony import */ var _getLogRowStyles__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./getLogRowStyles */ "./packages/grafana-ui/src/components/Logs/getLogRowStyles.ts");



// @ts-ignore












/**
 * Renders a highlighted field.
 * When hovering, a stats icon is shown.
 */
var FieldHighlight = function (onClick) { return function (props) {
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_index__WEBPACK_IMPORTED_MODULE_7__["ThemeContext"]);
    var style = Object(_getLogRowStyles__WEBPACK_IMPORTED_MODULE_14__["getLogRowStyles"])(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: props.className, style: props.style },
        props.children,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style, 'logs-row__field-highlight--icon', 'fa fa-signal']), onClick: function () { return onClick(props.children); } })));
}; };
var logRowStyles = Object(emotion__WEBPACK_IMPORTED_MODULE_6__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n  position: relative;\n  /* z-index: 0; */\n  /* outline: none; */\n"], ["\n  position: relative;\n  /* z-index: 0; */\n  /* outline: none; */\n"])));
var getLogRowWithContextStyles = function (theme, state) {
    var outlineColor = Object(_index__WEBPACK_IMPORTED_MODULE_7__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.black,
    }, theme.type);
    return {
        row: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      z-index: 1;\n      outline: 9999px solid\n        ", ";\n    "], ["\n      z-index: 1;\n      outline: 9999px solid\n        ",
            ";\n    "])), tinycolor2__WEBPACK_IMPORTED_MODULE_5___default()(outlineColor)
            .setAlpha(0.7)
            .toRgbString()),
    };
};
/**
 * Renders a log line.
 *
 * When user hovers over it for a certain time, it lazily parses the log line.
 * Once a parser is found, it will determine fields, that will be highlighted.
 * When the user requests stats for a field, they will be calculated and rendered below the row.
 */
var UnThemedLogRow = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UnThemedLogRow, _super);
    function UnThemedLogRow() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.mouseMessageTimer = null;
        _this.state = {
            fieldCount: 0,
            fieldLabel: null,
            fieldStats: null,
            fieldValue: null,
            parsed: false,
            parser: undefined,
            parsedFieldHighlights: [],
            showFieldStats: false,
            showContext: false,
        };
        _this.onClickClose = function () {
            _this.setState({ showFieldStats: false });
        };
        _this.onClickHighlight = function (fieldText) {
            var getRows = _this.props.getRows;
            var parser = _this.state.parser;
            var allRows = getRows();
            // Build value-agnostic row matcher based on the field label
            var fieldLabel = parser.getLabelFromField(fieldText);
            var fieldValue = parser.getValueFromField(fieldText);
            var matcher = parser.buildMatcher(fieldLabel);
            var fieldStats = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["calculateFieldStats"])(allRows, matcher);
            var fieldCount = fieldStats.reduce(function (sum, stat) { return sum + stat.count; }, 0);
            _this.setState({ fieldCount: fieldCount, fieldLabel: fieldLabel, fieldStats: fieldStats, fieldValue: fieldValue, showFieldStats: true });
        };
        _this.onMouseOverMessage = function () {
            if (_this.state.showContext || _this.isTextSelected()) {
                // When showing context we don't want to the LogRow rerender as it will mess up state of context block
                // making the "after" context to be scrolled to the top, what is desired only on open
                // The log row message needs to be refactored to separate component that encapsulates parsing and parsed message state
                return;
            }
            // Don't parse right away, user might move along
            _this.mouseMessageTimer = window.setTimeout(_this.parseMessage, 500);
        };
        _this.onMouseOutMessage = function () {
            if (_this.state.showContext) {
                // See comment in onMouseOverMessage method
                return;
            }
            _this.clearMouseMessageTimer();
            _this.setState({ parsed: false });
        };
        _this.clearMouseMessageTimer = function () {
            if (_this.mouseMessageTimer) {
                clearTimeout(_this.mouseMessageTimer);
            }
        };
        _this.parseMessage = function () {
            if (!_this.state.parsed) {
                var row = _this.props.row;
                var parser = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["getParser"])(row.entry);
                if (parser) {
                    // Use parser to highlight detected fields
                    var parsedFieldHighlights = parser.getFields(_this.props.row.entry);
                    _this.setState({ parsedFieldHighlights: parsedFieldHighlights, parsed: true, parser: parser });
                }
            }
        };
        _this.toggleContext = function () {
            _this.setState(function (state) {
                return {
                    showContext: !state.showContext,
                };
            });
        };
        _this.onContextToggle = function (e) {
            e.stopPropagation();
            _this.toggleContext();
        };
        return _this;
    }
    UnThemedLogRow.prototype.componentWillUnmount = function () {
        this.clearMouseMessageTimer();
    };
    UnThemedLogRow.prototype.isTextSelected = function () {
        if (!window.getSelection) {
            return false;
        }
        var selection = window.getSelection();
        if (!selection) {
            return false;
        }
        return selection.anchorNode !== null && selection.isCollapsed === false;
    };
    UnThemedLogRow.prototype.renderLogRow = function (context, errors, hasMoreContextRows, updateLimit) {
        var _this = this;
        var _a = this.props, getRows = _a.getRows, highlighterExpressions = _a.highlighterExpressions, onClickLabel = _a.onClickLabel, row = _a.row, showDuplicates = _a.showDuplicates, showLabels = _a.showLabels, timeZone = _a.timeZone, showTime = _a.showTime, theme = _a.theme;
        var _b = this.state, fieldCount = _b.fieldCount, fieldLabel = _b.fieldLabel, fieldStats = _b.fieldStats, fieldValue = _b.fieldValue, parsed = _b.parsed, parsedFieldHighlights = _b.parsedFieldHighlights, showFieldStats = _b.showFieldStats, showContext = _b.showContext;
        var style = Object(_getLogRowStyles__WEBPACK_IMPORTED_MODULE_14__["getLogRowStyles"])(theme, row.logLevel);
        var entry = row.entry, hasAnsi = row.hasAnsi, raw = row.raw;
        var previewHighlights = highlighterExpressions && !lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isEqual(highlighterExpressions, row.searchWords);
        var highlights = previewHighlights ? highlighterExpressions : row.searchWords;
        var needsHighlighter = highlights && highlights.length > 0 && highlights[0] && highlights[0].length > 0;
        var highlightClassName = previewHighlights
            ? Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowMatchHighLight, style.logsRowMatchHighLightPreview])
            : Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowMatchHighLight]);
        var showUtc = timeZone === 'utc';
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_7__["ThemeContext"].Consumer, null, function (theme) {
            var styles = _this.state.showContext
                ? Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])(logRowStyles, getLogRowWithContextStyles(theme, _this.state).row)
                : logRowStyles;
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRow]) },
                showDuplicates && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowDuplicates]) }, row.duplicates && row.duplicates > 0 ? row.duplicates + 1 + "x" : null)),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowLevel]) }),
                showTime && showUtc && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowLocalTime]), title: "Local: " + row.timeLocal + " (" + row.timeFromNow + ")" }, row.timeUtc)),
                showTime && !showUtc && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowLocalTime]), title: row.timeUtc + " (" + row.timeFromNow + ")" }, row.timeLocal)),
                showLabels && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowLabels]) },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabels__WEBPACK_IMPORTED_MODULE_10__["LogLabels"], { getRows: getRows, labels: row.uniqueLabels ? row.uniqueLabels : {}, onClickLabel: onClickLabel }))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowMessage]), onMouseEnter: _this.onMouseOverMessage, onMouseLeave: _this.onMouseOutMessage },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                    position: relative;\n                  "], ["\n                    position: relative;\n                  "]))) },
                        showContext && context && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogRowContext__WEBPACK_IMPORTED_MODULE_9__["LogRowContext"], { row: row, context: context, errors: errors, hasMoreContextRows: hasMoreContextRows, onOutsideClick: _this.toggleContext, onLoadMoreContext: function () {
                                if (updateLimit) {
                                    updateLimit();
                                }
                            } })),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: styles },
                            parsed && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_highlight_words__WEBPACK_IMPORTED_MODULE_3___default.a, { style: { whiteSpace: 'pre-wrap' }, autoEscape: true, highlightTag: FieldHighlight(_this.onClickHighlight), textToHighlight: entry, searchWords: parsedFieldHighlights, highlightClassName: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowFieldHighLight]) })),
                            !parsed && needsHighlighter && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_highlight_words__WEBPACK_IMPORTED_MODULE_3___default.a, { style: { whiteSpace: 'pre-wrap' }, textToHighlight: entry, searchWords: highlights, findChunks: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["findHighlightChunksInText"], highlightClassName: highlightClassName })),
                            hasAnsi && !parsed && !needsHighlighter && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogMessageAnsi__WEBPACK_IMPORTED_MODULE_11__["LogMessageAnsi"], { value: raw }),
                            !hasAnsi && !parsed && !needsHighlighter && entry,
                            showFieldStats && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["cx"])([style.logsRowStats]) },
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogLabelStats__WEBPACK_IMPORTED_MODULE_12__["LogLabelStats"], { stats: fieldStats, label: fieldLabel, value: fieldValue, onClickClose: _this.onClickClose, rowCount: fieldCount })))),
                        row.searchWords && row.searchWords.length > 0 && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { onClick: _this.onContextToggle, className: Object(emotion__WEBPACK_IMPORTED_MODULE_6__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                        visibility: hidden;\n                        white-space: nowrap;\n                        position: relative;\n                        z-index: ", ";\n                        cursor: pointer;\n                        .", ":hover & {\n                          visibility: visible;\n                          margin-left: 10px;\n                          text-decoration: underline;\n                        }\n                      "], ["\n                        visibility: hidden;\n                        white-space: nowrap;\n                        position: relative;\n                        z-index: ", ";\n                        cursor: pointer;\n                        .", ":hover & {\n                          visibility: visible;\n                          margin-left: 10px;\n                          text-decoration: underline;\n                        }\n                      "])), showContext ? 1 : 0, style.logsRow) },
                            showContext ? 'Hide' : 'Show',
                            " context"))))));
        }));
    };
    UnThemedLogRow.prototype.render = function () {
        var _this = this;
        var showContext = this.state.showContext;
        if (showContext) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogRowContextProvider__WEBPACK_IMPORTED_MODULE_8__["LogRowContextProvider"], { row: this.props.row, getRowContext: this.props.getRowContext }, function (_a) {
                    var result = _a.result, errors = _a.errors, hasMoreContextRows = _a.hasMoreContextRows, updateLimit = _a.updateLimit;
                    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, _this.renderLogRow(result, errors, hasMoreContextRows, updateLimit));
                })));
        }
        return this.renderLogRow();
    };
    return UnThemedLogRow;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
var LogRow = Object(_themes_index__WEBPACK_IMPORTED_MODULE_13__["withTheme"])(UnThemedLogRow);
LogRow.displayName = 'LogRow';
var templateObject_1, templateObject_2, templateObject_3, templateObject_4;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogRowContext.tsx":
/*!*******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogRowContext.tsx ***!
  \*******************************************************************/
/*! exports provided: LogRowContext */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogRowContext", function() { return LogRowContext; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _Alert_Alert__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Alert/Alert */ "./packages/grafana-ui/src/components/Alert/Alert.tsx");
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var _CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../CustomScrollbar/CustomScrollbar */ "./packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx");
/* harmony import */ var _List_List__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../List/List */ "./packages/grafana-ui/src/components/List/List.tsx");
/* harmony import */ var _ClickOutsideWrapper_ClickOutsideWrapper__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../ClickOutsideWrapper/ClickOutsideWrapper */ "./packages/grafana-ui/src/components/ClickOutsideWrapper/ClickOutsideWrapper.tsx");









var getLogRowContextStyles = function (theme) {
    var gradientTop = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.dark1,
    }, theme.type);
    var gradientBottom = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray7,
        dark: theme.colors.dark2,
    }, theme.type);
    var boxShadowColor = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray5,
        dark: theme.colors.black,
    }, theme.type);
    var borderColor = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.gray5,
        dark: theme.colors.dark9,
    }, theme.type);
    return {
        commonStyles: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      position: absolute;\n      width: calc(100% + 20px);\n      left: -10px;\n      height: 250px;\n      z-index: 2;\n      overflow: hidden;\n      background: ", ";\n      background: linear-gradient(180deg, ", " 0%, ", " 104.25%);\n      box-shadow: 0px 2px 4px ", ", 0px 0px 2px ", ";\n      border: 1px solid ", ";\n      border-radius: ", ";\n    "], ["\n      position: absolute;\n      width: calc(100% + 20px);\n      left: -10px;\n      height: 250px;\n      z-index: 2;\n      overflow: hidden;\n      background: ", ";\n      background: linear-gradient(180deg, ", " 0%, ", " 104.25%);\n      box-shadow: 0px 2px 4px ", ", 0px 0px 2px ", ";\n      border: 1px solid ", ";\n      border-radius: ", ";\n    "])), theme.colors.pageBg, gradientTop, gradientBottom, boxShadowColor, boxShadowColor, borderColor, theme.border.radius.md),
        header: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      height: 30px;\n      padding: 0 10px;\n      display: flex;\n      align-items: center;\n      background: ", ";\n    "], ["\n      height: 30px;\n      padding: 0 10px;\n      display: flex;\n      align-items: center;\n      background: ", ";\n    "])), borderColor),
        logs: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      height: 220px;\n      padding: 10px;\n    "], ["\n      height: 220px;\n      padding: 10px;\n    "]))),
    };
};
var LogRowContextGroupHeader = function (_a) {
    var row = _a.row, rows = _a.rows, onLoadMoreContext = _a.onLoadMoreContext, canLoadMoreRows = _a.canLoadMoreRows;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__["ThemeContext"]);
    var header = getLogRowContextStyles(theme).header;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: header },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n          opacity: 0.6;\n        "], ["\n          opacity: 0.6;\n        "]))) },
            "Found ",
            rows.length,
            " rows."),
        (rows.length >= 10 || (rows.length > 10 && rows.length % 10 !== 0)) && canLoadMoreRows && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n            margin-left: 10px;\n            &:hover {\n              text-decoration: underline;\n              cursor: pointer;\n            }\n          "], ["\n            margin-left: 10px;\n            &:hover {\n              text-decoration: underline;\n              cursor: pointer;\n            }\n          "]))), onClick: function () { return onLoadMoreContext(); } }, "Load 10 more"))));
};
var LogRowContextGroup = function (_a) {
    var row = _a.row, rows = _a.rows, error = _a.error, className = _a.className, shouldScrollToBottom = _a.shouldScrollToBottom, canLoadMoreRows = _a.canLoadMoreRows, onLoadMoreContext = _a.onLoadMoreContext;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_5__["ThemeContext"]);
    var _b = getLogRowContextStyles(theme), commonStyles = _b.commonStyles, logs = _b.logs;
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(0), 2), scrollTop = _c[0], setScrollTop = _c[1];
    var listContainerRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["useRef"])();
    Object(react__WEBPACK_IMPORTED_MODULE_1__["useLayoutEffect"])(function () {
        if (shouldScrollToBottom && listContainerRef.current) {
            setScrollTop(listContainerRef.current.offsetHeight);
        }
    });
    var headerProps = {
        row: row,
        rows: rows,
        onLoadMoreContext: onLoadMoreContext,
        canLoadMoreRows: canLoadMoreRows,
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])(className, commonStyles) },
        shouldScrollToBottom && !error && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LogRowContextGroupHeader, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, headerProps)),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: logs },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_6__["CustomScrollbar"], { autoHide: true, scrollTop: scrollTop },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: listContainerRef },
                    !error && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_List_List__WEBPACK_IMPORTED_MODULE_7__["List"], { items: rows, renderItem: function (item) {
                            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                        padding: 5px 0;\n                      "], ["\n                        padding: 5px 0;\n                      "]))) }, item));
                        } })),
                    error && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Alert_Alert__WEBPACK_IMPORTED_MODULE_3__["Alert"], { title: error })))),
        !shouldScrollToBottom && !error && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LogRowContextGroupHeader, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, headerProps))));
};
var LogRowContext = function (_a) {
    var row = _a.row, context = _a.context, errors = _a.errors, onOutsideClick = _a.onOutsideClick, onLoadMoreContext = _a.onLoadMoreContext, hasMoreContextRows = _a.hasMoreContextRows;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ClickOutsideWrapper_ClickOutsideWrapper__WEBPACK_IMPORTED_MODULE_8__["ClickOutsideWrapper"], { onClick: onOutsideClick },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
            context.after && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LogRowContextGroup, { rows: context.after, error: errors && errors.after, row: row, className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_7 || (templateObject_7 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n              top: -250px;\n            "], ["\n              top: -250px;\n            "]))), shouldScrollToBottom: true, canLoadMoreRows: hasMoreContextRows ? hasMoreContextRows.after : false, onLoadMoreContext: onLoadMoreContext })),
            context.before && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LogRowContextGroup, { onLoadMoreContext: onLoadMoreContext, canLoadMoreRows: hasMoreContextRows ? hasMoreContextRows.before : false, row: row, rows: context.before, error: errors && errors.before, className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_8 || (templateObject_8 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n              top: 100%;\n            "], ["\n              top: 100%;\n            "]))) })))));
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8;


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogRowContextProvider.tsx":
/*!***************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogRowContextProvider.tsx ***!
  \***************************************************************************/
/*! exports provided: getRowContexts, LogRowContextProvider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRowContexts", function() { return getRowContexts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogRowContextProvider", function() { return LogRowContextProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_flatten__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/flatten */ "./node_modules/lodash/flatten.js");
/* harmony import */ var lodash_flatten__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_flatten__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var react_use_lib_useAsync__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-use/lib/useAsync */ "./node_modules/react-use/lib/useAsync.js");
/* harmony import */ var react_use_lib_useAsync__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_use_lib_useAsync__WEBPACK_IMPORTED_MODULE_4__);
var _this = undefined;





var getRowContexts = function (getRowContext, row, limit) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    var promises, results;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0:
                promises = [
                    getRowContext(row, {
                        limit: limit,
                    }),
                    getRowContext(row, {
                        limit: limit + 1,
                        direction: 'FORWARD',
                    }),
                ];
                return [4 /*yield*/, Promise.all(promises.map(function (p) { return p.catch(function (e) { return e; }); }))];
            case 1:
                results = _a.sent();
                return [2 /*return*/, {
                        data: results.map(function (result) {
                            var dataResult = result;
                            if (!dataResult.data) {
                                return [];
                            }
                            var data = [];
                            for (var index = 0; index < dataResult.data.length; index++) {
                                var dataFrame = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["toDataFrame"])(dataResult.data[index]);
                                var timestampField = dataFrame.fields.filter(function (field) { return field.name === 'ts'; })[0];
                                for (var fieldIndex = 0; fieldIndex < timestampField.values.length; fieldIndex++) {
                                    var timestamp = timestampField.values.get(fieldIndex);
                                    // We need to filter out the row we're basing our search from because of how start/end params work in Loki API
                                    // see https://github.com/grafana/loki/issues/597#issuecomment-506408980
                                    // the alternative to create our own add 1 nanosecond method to the a timestamp string would be quite complex
                                    if (timestamp === row.timestamp) {
                                        continue;
                                    }
                                    var lineField = dataFrame.fields.filter(function (field) { return field.name === 'line'; })[0];
                                    var line = lineField.values.get(fieldIndex); // assuming that both fields have same length
                                    if (data.length === 0) {
                                        data[0] = [line];
                                    }
                                    else {
                                        data[0].push(line);
                                    }
                                }
                            }
                            return data;
                        }),
                        errors: results.map(function (result) {
                            var errorResult = result;
                            if (!errorResult.message) {
                                return '';
                            }
                            return errorResult.message;
                        }),
                    }];
        }
    });
}); };
var LogRowContextProvider = function (_a) {
    var getRowContext = _a.getRowContext, row = _a.row, children = _a.children;
    // React Hook that creates a number state value called limit to component state and a setter function called setLimit
    // The intial value for limit is 10
    // Used for the number of rows to retrieve from backend from a specific point in time
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_2__["useState"])(10), 2), limit = _b[0], setLimit = _b[1];
    // React Hook that creates an object state value called result to component state and a setter function called setResult
    // The intial value for result is null
    // Used for sorting the response from backend
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_2__["useState"])(null), 2), result = _c[0], setResult = _c[1];
    // React Hook that creates an object state value called hasMoreContextRows to component state and a setter function called setHasMoreContextRows
    // The intial value for hasMoreContextRows is {before: true, after: true}
    // Used for indicating in UI if there are more rows to load in a given direction
    var _d = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_2__["useState"])({
        before: true,
        after: true,
    }), 2), hasMoreContextRows = _d[0], setHasMoreContextRows = _d[1];
    // React Hook that resolves two promises every time the limit prop changes
    // First promise fetches limit number of rows backwards in time from a specific point in time
    // Second promise fetches limit number of rows forwards in time from a specific point in time
    var value = react_use_lib_useAsync__WEBPACK_IMPORTED_MODULE_4___default()(function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, getRowContexts(getRowContext, row, limit)];
                case 1: return [2 /*return*/, _a.sent()]; // Moved it to a separate function for debugging purposes
            }
        });
    }); }, [limit]).value;
    // React Hook that performs a side effect every time the value (from useAsync hook) prop changes
    // The side effect changes the result state with the response from the useAsync hook
    // The side effect changes the hasMoreContextRows state if there are more context rows before or after the current result
    Object(react__WEBPACK_IMPORTED_MODULE_2__["useEffect"])(function () {
        if (value) {
            setResult(function (currentResult) {
                var hasMoreLogsBefore = true, hasMoreLogsAfter = true;
                if (currentResult && currentResult.data[0].length === value.data[0].length) {
                    hasMoreLogsBefore = false;
                }
                if (currentResult && currentResult.data[1].length === value.data[1].length) {
                    hasMoreLogsAfter = false;
                }
                setHasMoreContextRows({
                    before: hasMoreLogsBefore,
                    after: hasMoreLogsAfter,
                });
                return value;
            });
        }
    }, [value]);
    return children({
        result: {
            before: result ? lodash_flatten__WEBPACK_IMPORTED_MODULE_3___default()(result.data[0]) : [],
            after: result ? lodash_flatten__WEBPACK_IMPORTED_MODULE_3___default()(result.data[1]) : [],
        },
        errors: {
            before: result ? result.errors[0] : undefined,
            after: result ? result.errors[1] : undefined,
        },
        hasMoreContextRows: hasMoreContextRows,
        updateLimit: function () { return setLimit(limit + 10); },
    });
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/LogRows.tsx":
/*!*************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/LogRows.tsx ***!
  \*************************************************************/
/*! exports provided: LogRows */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogRows", function() { return LogRows; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _LogRow__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LogRow */ "./packages/grafana-ui/src/components/Logs/LogRow.tsx");
/* harmony import */ var _themes_index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../themes/index */ "./packages/grafana-ui/src/themes/index.ts");
/* harmony import */ var _getLogRowStyles__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./getLogRowStyles */ "./packages/grafana-ui/src/components/Logs/getLogRowStyles.ts");







var PREVIEW_LIMIT = 100;
var RENDER_LIMIT = 500;
var UnThemedLogRows = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UnThemedLogRows, _super);
    function UnThemedLogRows() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.deferLogsTimer = null;
        _this.renderAllTimer = null;
        _this.state = {
            deferLogs: true,
            renderAll: false,
        };
        return _this;
    }
    UnThemedLogRows.prototype.componentDidMount = function () {
        var _this = this;
        // Staged rendering
        if (this.state.deferLogs) {
            var data = this.props.data;
            var rowCount = data && data.rows ? data.rows.length : 0;
            // Render all right away if not too far over the limit
            var renderAll_1 = rowCount <= PREVIEW_LIMIT * 2;
            this.deferLogsTimer = window.setTimeout(function () { return _this.setState({ deferLogs: false, renderAll: renderAll_1 }); }, rowCount);
        }
    };
    UnThemedLogRows.prototype.componentDidUpdate = function (prevProps, prevState) {
        var _this = this;
        // Staged rendering
        if (prevState.deferLogs && !this.state.deferLogs && !this.state.renderAll) {
            this.renderAllTimer = window.setTimeout(function () { return _this.setState({ renderAll: true }); }, 2000);
        }
    };
    UnThemedLogRows.prototype.componentWillUnmount = function () {
        if (this.deferLogsTimer) {
            clearTimeout(this.deferLogsTimer);
        }
        if (this.renderAllTimer) {
            clearTimeout(this.renderAllTimer);
        }
    };
    UnThemedLogRows.prototype.render = function () {
        var _a = this.props, dedupStrategy = _a.dedupStrategy, showTime = _a.showTime, data = _a.data, deduplicatedData = _a.deduplicatedData, highlighterExpressions = _a.highlighterExpressions, showLabels = _a.showLabels, timeZone = _a.timeZone, onClickLabel = _a.onClickLabel, rowLimit = _a.rowLimit, theme = _a.theme;
        var _b = this.state, deferLogs = _b.deferLogs, renderAll = _b.renderAll;
        var dedupedData = deduplicatedData ? deduplicatedData : data;
        var hasData = data && data.rows && data.rows.length > 0;
        var hasLabel = hasData && dedupedData && dedupedData.hasUniqueLabels ? true : false;
        var dedupCount = dedupedData
            ? dedupedData.rows.reduce(function (sum, row) { return (row.duplicates ? sum + row.duplicates : sum); }, 0)
            : 0;
        var showDuplicates = dedupStrategy !== _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"].none && dedupCount > 0;
        // Staged rendering
        var processedRows = dedupedData ? dedupedData.rows : [];
        var firstRows = processedRows.slice(0, PREVIEW_LIMIT);
        var renderLimit = rowLimit || RENDER_LIMIT;
        var rowCount = Math.min(processedRows.length, renderLimit);
        var lastRows = processedRows.slice(PREVIEW_LIMIT, rowCount);
        // React profiler becomes unusable if we pass all rows to all rows and their labels, using getter instead
        var getRows = function () { return processedRows; };
        var getRowContext = this.props.getRowContext ? this.props.getRowContext : function () { return Promise.resolve([]); };
        var logsRows = Object(_getLogRowStyles__WEBPACK_IMPORTED_MODULE_6__["getLogRowStyles"])(theme).logsRows;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([logsRows]) },
            hasData &&
                !deferLogs && // Only inject highlighterExpression in the first set for performance reasons
                firstRows.map(function (row, index) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogRow__WEBPACK_IMPORTED_MODULE_4__["LogRow"], { key: index, getRows: getRows, getRowContext: getRowContext, highlighterExpressions: highlighterExpressions, row: row, showDuplicates: showDuplicates, showLabels: showLabels && hasLabel, showTime: showTime, timeZone: timeZone, onClickLabel: onClickLabel })); }),
            hasData &&
                !deferLogs &&
                renderAll &&
                lastRows.map(function (row, index) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LogRow__WEBPACK_IMPORTED_MODULE_4__["LogRow"], { key: PREVIEW_LIMIT + index, getRows: getRows, getRowContext: getRowContext, row: row, showDuplicates: showDuplicates, showLabels: showLabels && hasLabel, showTime: showTime, timeZone: timeZone, onClickLabel: onClickLabel })); }),
            hasData && deferLogs && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null,
                "Rendering ",
                rowCount,
                " rows...")));
    };
    return UnThemedLogRows;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
var LogRows = Object(_themes_index__WEBPACK_IMPORTED_MODULE_5__["withTheme"])(UnThemedLogRows);
LogRows.displayName = 'LogsRows';


/***/ }),

/***/ "./packages/grafana-ui/src/components/Logs/getLogRowStyles.ts":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Logs/getLogRowStyles.ts ***!
  \********************************************************************/
/*! exports provided: getLogRowStyles */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLogRowStyles", function() { return getLogRowStyles; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes/selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");




var getLogRowStyles = function (theme, logLevel) {
    var logColor = Object(_themes_selectThemeVariant__WEBPACK_IMPORTED_MODULE_3__["selectThemeVariant"])({ light: theme.colors.gray5, dark: theme.colors.gray2 }, theme.type);
    switch (logLevel) {
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].crit:
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].critical:
            logColor = '#705da0';
            break;
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].error:
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].err:
            logColor = '#e24d42';
            break;
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].warning:
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].warn:
            logColor = theme.colors.yellow;
            break;
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].info:
            logColor = '#7eb26d';
            break;
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].debug:
            logColor = '#1f78c1';
            break;
        case _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogLevel"].trace:
            logColor = '#6ed0e0';
            break;
    }
    return {
        logsRowFieldHighLight: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__field-highlight;\n      background: inherit;\n      padding: inherit;\n      border-bottom: 1px dotted ", ";\n\n      .logs-row__field-highlight--icon {\n        margin-left: 0.5em;\n        cursor: pointer;\n        display: none;\n      }\n\n      &:hover {\n        color: ", ";\n        border-bottom-style: solid;\n\n        .logs-row__field-highlight--icon {\n          display: inline;\n        }\n      }\n    "], ["\n      label: logs-row__field-highlight;\n      background: inherit;\n      padding: inherit;\n      border-bottom: 1px dotted ", ";\n\n      .logs-row__field-highlight--icon {\n        margin-left: 0.5em;\n        cursor: pointer;\n        display: none;\n      }\n\n      &:hover {\n        color: ", ";\n        border-bottom-style: solid;\n\n        .logs-row__field-highlight--icon {\n          display: inline;\n        }\n      }\n    "])), theme.colors.yellow, theme.colors.yellow),
        logsRowMatchHighLight: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__match-highlight;\n      background: inherit;\n      padding: inherit;\n\n      color: ", ";\n      border-bottom: 1px solid ", ";\n      background-color: rgba(", ", 0.1);\n    "], ["\n      label: logs-row__match-highlight;\n      background: inherit;\n      padding: inherit;\n\n      color: ", ";\n      border-bottom: 1px solid ", ";\n      background-color: rgba(", ", 0.1);\n    "])), theme.colors.yellow, theme.colors.yellow, theme.colors.yellow),
        logsRowMatchHighLightPreview: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__match-highlight--preview;\n      background-color: rgba(", ", 0.2);\n      border-bottom-style: dotted;\n    "], ["\n      label: logs-row__match-highlight--preview;\n      background-color: rgba(", ", 0.2);\n      border-bottom-style: dotted;\n    "])), theme.colors.yellow),
        logsRows: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-rows;\n      font-family: ", ";\n      font-size: ", ";\n      display: table;\n      table-layout: fixed;\n      width: 100%;\n    "], ["\n      label: logs-rows;\n      font-family: ", ";\n      font-size: ", ";\n      display: table;\n      table-layout: fixed;\n      width: 100%;\n    "])), theme.typography.fontFamily.monospace, theme.typography.size.sm),
        logsRow: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row;\n      display: table-row;\n\n      > div {\n        display: table-cell;\n        padding-right: 10px;\n        border-top: 1px solid transparent;\n        border-bottom: 1px solid transparent;\n        height: 100%;\n      }\n\n      &:hover {\n        background: ", ";\n      }\n    "], ["\n      label: logs-row;\n      display: table-row;\n\n      > div {\n        display: table-cell;\n        padding-right: 10px;\n        border-top: 1px solid transparent;\n        border-bottom: 1px solid transparent;\n        height: 100%;\n      }\n\n      &:hover {\n        background: ", ";\n      }\n    "])), theme.colors.pageBg),
        logsRowDuplicates: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__duplicates;\n      text-align: right;\n      width: 4em;\n    "], ["\n      label: logs-row__duplicates;\n      text-align: right;\n      width: 4em;\n    "]))),
        logsRowLevel: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_7 || (templateObject_7 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__level;\n      position: relative;\n      width: 10px;\n\n      &::after {\n        content: '';\n        display: block;\n        position: absolute;\n        top: 1px;\n        bottom: 1px;\n        width: 3px;\n        background-color: ", ";\n      }\n    "], ["\n      label: logs-row__level;\n      position: relative;\n      width: 10px;\n\n      &::after {\n        content: '';\n        display: block;\n        position: absolute;\n        top: 1px;\n        bottom: 1px;\n        width: 3px;\n        background-color: ", ";\n      }\n    "])), logColor),
        logsRowLocalTime: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_8 || (templateObject_8 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__localtime;\n      white-space: nowrap;\n      width: 12.5em;\n    "], ["\n      label: logs-row__localtime;\n      white-space: nowrap;\n      width: 12.5em;\n    "]))),
        logsRowLabels: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_9 || (templateObject_9 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__labels;\n      width: 20%;\n      line-height: 1.2;\n      position: relative;\n    "], ["\n      label: logs-row__labels;\n      width: 20%;\n      line-height: 1.2;\n      position: relative;\n    "]))),
        logsRowMessage: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_10 || (templateObject_10 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__message;\n      word-break: break-all;\n    "], ["\n      label: logs-row__message;\n      word-break: break-all;\n    "]))),
        logsRowStats: Object(emotion__WEBPACK_IMPORTED_MODULE_1__["css"])(templateObject_11 || (templateObject_11 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: logs-row__stats;\n      margin: 5px 0;\n    "], ["\n      label: logs-row__stats;\n      margin: 5px 0;\n    "]))),
    };
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6, templateObject_7, templateObject_8, templateObject_9, templateObject_10, templateObject_11;


/***/ }),

/***/ "./packages/grafana-ui/src/components/PanelOptionsGrid/PanelOptionsGrid.tsx":
/*!**********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/PanelOptionsGrid/PanelOptionsGrid.tsx ***!
  \**********************************************************************************/
/*! exports provided: PanelOptionsGrid */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelOptionsGrid", function() { return PanelOptionsGrid; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var PanelOptionsGrid = function (_a) {
    var children = _a.children;
    return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-options-grid" }, children);
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/PanelOptionsGroup/PanelOptionsGroup.tsx":
/*!************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/PanelOptionsGroup/PanelOptionsGroup.tsx ***!
  \************************************************************************************/
/*! exports provided: PanelOptionsGroup */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelOptionsGroup", function() { return PanelOptionsGroup; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
// Libraries

var PanelOptionsGroup = function (props) {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-options-group" },
        props.onAdd ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-options-group__header" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { className: "panel-options-group__add-btn", onClick: props.onAdd },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-options-group__add-circle" },
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-plus" })),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "panel-options-group__title" }, props.title)))) : (props.title && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-options-group__header" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "panel-options-group__title" }, props.title),
            props.onClose && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { className: "btn btn-link", onClick: props.onClose },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-remove" })))))),
        props.children && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-options-group__body" }, props.children)));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/PieChart/PieChart.tsx":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/components/PieChart/PieChart.tsx ***!
  \******************************************************************/
/*! exports provided: PieChartType, PieChart */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PieChartType", function() { return PieChartType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PieChart", function() { return PieChart; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! d3 */ "./node_modules/d3/index.js");
/* harmony import */ var lodash_sum__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/sum */ "./node_modules/lodash/sum.js");
/* harmony import */ var lodash_sum__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_sum__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../types */ "./packages/grafana-ui/src/types/index.ts");
/* harmony import */ var _utils_index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils/index */ "./packages/grafana-ui/src/utils/index.ts");






var PieChartType;
(function (PieChartType) {
    PieChartType["PIE"] = "pie";
    PieChartType["DONUT"] = "donut";
})(PieChartType || (PieChartType = {}));
var PieChart = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PieChart, _super);
    function PieChart() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PieChart.prototype.componentDidMount = function () {
        this.draw();
    };
    PieChart.prototype.componentDidUpdate = function () {
        this.draw();
    };
    PieChart.prototype.draw = function () {
        var _this = this;
        var _a = this.props, values = _a.values, pieType = _a.pieType, strokeWidth = _a.strokeWidth;
        if (values.length === 0) {
            return;
        }
        var data = values.map(function (datapoint) { return datapoint.numeric; });
        var names = values.map(function (datapoint) { return datapoint.text; });
        var colors = values.map(function (p, idx) {
            if (p.color) {
                return p.color;
            }
            return _utils_index__WEBPACK_IMPORTED_MODULE_5__["colors"][idx % _utils_index__WEBPACK_IMPORTED_MODULE_5__["colors"].length];
        });
        var total = lodash_sum__WEBPACK_IMPORTED_MODULE_3___default()(data) || 1;
        var percents = data.map(function (item) { return (item / total) * 100; });
        var width = this.containerElement.offsetWidth;
        var height = this.containerElement.offsetHeight;
        var radius = Math.min(width, height) / 2;
        var outerRadius = radius - radius / 10;
        var innerRadius = pieType === PieChartType.PIE ? 0 : radius - radius / 3;
        var svg = Object(d3__WEBPACK_IMPORTED_MODULE_2__["select"])(this.svgElement)
            .html('')
            .attr('width', width)
            .attr('height', height)
            .append('g')
            .attr('transform', "translate(" + width / 2 + "," + height / 2 + ")");
        var pieChart = Object(d3__WEBPACK_IMPORTED_MODULE_2__["pie"])();
        var customArc = Object(d3__WEBPACK_IMPORTED_MODULE_2__["arc"])()
            .outerRadius(outerRadius)
            .innerRadius(innerRadius)
            .padAngle(0);
        svg
            .selectAll('path')
            .data(pieChart(data))
            .enter()
            .append('path')
            .attr('d', customArc)
            .attr('fill', function (d, idx) { return colors[idx]; })
            .style('fill-opacity', 0.15)
            .style('stroke', function (d, idx) { return colors[idx]; })
            .style('stroke-width', strokeWidth + "px")
            .on('mouseover', function (d, idx) {
            Object(d3__WEBPACK_IMPORTED_MODULE_2__["select"])(_this.tooltipElement).style('opacity', 1);
            Object(d3__WEBPACK_IMPORTED_MODULE_2__["select"])(_this.tooltipValueElement).text(names[idx] + " (" + percents[idx].toFixed(2) + "%)");
        })
            .on('mousemove', function () {
            Object(d3__WEBPACK_IMPORTED_MODULE_2__["select"])(_this.tooltipElement)
                .style('top', d3__WEBPACK_IMPORTED_MODULE_2__["event"].pageY - height / 2 + "px")
                .style('left', d3__WEBPACK_IMPORTED_MODULE_2__["event"].pageX + "px");
        })
            .on('mouseout', function () {
            Object(d3__WEBPACK_IMPORTED_MODULE_2__["select"])(_this.tooltipElement).style('opacity', 0);
        });
    };
    PieChart.prototype.render = function () {
        var _this = this;
        var _a = this.props, height = _a.height, width = _a.width, values = _a.values;
        if (values.length > 0) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "piechart-panel" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: function (element) { return (_this.containerElement = element); }, className: "piechart-container", style: {
                        height: height * 0.9 + "px",
                        width: Math.min(width, height * 1.3) + "px",
                    } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("svg", { ref: function (element) { return (_this.svgElement = element); } })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "piechart-tooltip", ref: function (element) { return (_this.tooltipElement = element); } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "piechart-tooltip-time" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { id: "tooltip-value", className: "piechart-tooltip-value", ref: function (element) { return (_this.tooltipValueElement = element); } })))));
        }
        else {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "piechart-panel" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "datapoints-warning" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "small" }, "No data points"))));
        }
    };
    PieChart.defaultProps = {
        pieType: 'pie',
        format: 'short',
        stat: 'current',
        strokeWidth: 1,
        theme: _types__WEBPACK_IMPORTED_MODULE_4__["GrafanaThemeType"].Dark,
    };
    return PieChart;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Portal/Portal.tsx":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Portal/Portal.tsx ***!
  \**************************************************************/
/*! exports provided: Portal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Portal", function() { return Portal; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_2__);



var Portal = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Portal, _super);
    function Portal(props) {
        var _this = _super.call(this, props) || this;
        _this.node = document.createElement('div');
        var _a = _this.props, className = _a.className, _b = _a.root, root = _b === void 0 ? document.body : _b;
        if (className) {
            _this.node.classList.add(className);
        }
        _this.portalRoot = root;
        _this.portalRoot.appendChild(_this.node);
        return _this;
    }
    Portal.prototype.componentWillUnmount = function () {
        this.portalRoot.removeChild(this.node);
    };
    Portal.prototype.render = function () {
        return react_dom__WEBPACK_IMPORTED_MODULE_2___default.a.createPortal(this.props.children, this.node);
    };
    return Portal;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/RefreshPicker/RefreshPicker.tsx":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/RefreshPicker/RefreshPicker.tsx ***!
  \****************************************************************************/
/*! exports provided: offOption, liveOption, defaultIntervals, isLive, RefreshPickerBase, RefreshPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offOption", function() { return offOption; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "liveOption", function() { return liveOption; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultIntervals", function() { return defaultIntervals; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLive", function() { return isLive; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefreshPickerBase", function() { return RefreshPickerBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefreshPicker", function() { return RefreshPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");
/* harmony import */ var _Select_ButtonSelect__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Select/ButtonSelect */ "./packages/grafana-ui/src/components/Select/ButtonSelect.tsx");
/* harmony import */ var memoize_one__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! memoize-one */ "./node_modules/memoize-one/dist/memoize-one.esm.js");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");








var offOption = { label: 'Off', value: '' };
var liveOption = { label: 'Live', value: 'LIVE' };
var defaultIntervals = ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'];
var isLive = function (refreshInterval) { return refreshInterval === liveOption.value; };
var getStyles = Object(memoize_one__WEBPACK_IMPORTED_MODULE_6__["default"])(function (theme) {
    return {
        selectButton: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      label: selectButton;\n      .select-button-value {\n        color: ", ";\n      }\n    "], ["\n      label: selectButton;\n      .select-button-value {\n        color: ", ";\n      }\n    "])), theme.colors.orange),
    };
});
var RefreshPickerBase = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefreshPickerBase, _super);
    function RefreshPickerBase(props) {
        var _this = _super.call(this, props) || this;
        _this.intervalsToOptions = function (intervals) {
            var intervalsOrDefault = intervals || defaultIntervals;
            var options = intervalsOrDefault
                .filter(function (str) { return str !== ''; })
                .map(function (interval) { return ({ label: interval, value: interval }); });
            if (_this.props.hasLiveOption) {
                options.unshift(liveOption);
            }
            options.unshift(offOption);
            return options;
        };
        _this.onChangeSelect = function (item) {
            var onIntervalChanged = _this.props.onIntervalChanged;
            if (onIntervalChanged) {
                // @ts-ignore
                onIntervalChanged(item.value);
            }
        };
        return _this;
    }
    RefreshPickerBase.prototype.render = function () {
        var _a = this.props, onRefresh = _a.onRefresh, intervals = _a.intervals, tooltip = _a.tooltip, value = _a.value, refreshButton = _a.refreshButton, buttonSelectClassName = _a.buttonSelectClassName, theme = _a.theme;
        var options = this.intervalsToOptions(intervals);
        var currentValue = value || '';
        var selectedValue = options.find(function (item) { return item.value === currentValue; }) || offOption;
        var styles = getStyles(theme);
        var cssClasses = classnames__WEBPACK_IMPORTED_MODULE_2___default()({
            'refresh-picker': true,
            'refresh-picker--off': selectedValue.label === offOption.label,
            'refresh-picker--live': selectedValue === liveOption,
        });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: cssClasses },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "refresh-picker-buttons" },
                refreshButton ? (refreshButton) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_4__["Tooltip"], { placement: "top", content: tooltip },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn btn--radius-right-0 navbar-button navbar-button--border-right-0", onClick: onRefresh },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-refresh" })))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Select_ButtonSelect__WEBPACK_IMPORTED_MODULE_5__["ButtonSelect"], { className: classnames__WEBPACK_IMPORTED_MODULE_2___default()('navbar-button--attached', styles.selectButton, buttonSelectClassName), value: selectedValue, label: selectedValue.label, options: options, onChange: this.onChangeSelect, maxMenuHeight: 380 }))));
    };
    // Make it exported as static properties to be easier to access. The global exports need to be accessed by direct
    // import of this source file which won't work if this was installed as package.
    RefreshPickerBase.offOption = offOption;
    RefreshPickerBase.liveOption = liveOption;
    return RefreshPickerBase;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var RefreshPicker = Object(_themes__WEBPACK_IMPORTED_MODULE_7__["withTheme"])(RefreshPickerBase);
var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/SecretFormFied/SecretFormField.tsx":
/*!*******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/SecretFormFied/SecretFormField.tsx ***!
  \*******************************************************************************/
/*! exports provided: SecretFormField */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SecretFormField", function() { return SecretFormField; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_omit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/omit */ "./node_modules/lodash/omit.js");
/* harmony import */ var lodash_omit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_omit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! .. */ "./packages/grafana-ui/src/components/index.ts");




var defaultProps = {
    inputWidth: 12,
    placeholder: 'Password',
    label: 'Password',
};
/**
 * Form field that has 2 states configured and not configured. If configured it will not show its contents and adds
 * a reset button that will clear the input and makes it accessible. In non configured state it behaves like normal
 * form field. This is used for passwords or anything that is encrypted on the server and is later returned encrypted
 * to the user (like datasource passwords).
 */
var SecretFormField = function (_a) {
    var label = _a.label, labelWidth = _a.labelWidth, inputWidth = _a.inputWidth, onReset = _a.onReset, isConfigured = _a.isConfigured, placeholder = _a.placeholder, inputProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["label", "labelWidth", "inputWidth", "onReset", "isConfigured", "placeholder"]);
    return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(___WEBPACK_IMPORTED_MODULE_3__["FormField"], { label: label, labelWidth: labelWidth, inputEl: isConfigured ? (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_2___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("input", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ type: "text", className: "gf-form-input width-" + (inputWidth - 2), disabled: true, value: "configured" }, lodash_omit__WEBPACK_IMPORTED_MODULE_1___default()(inputProps, 'value'))),
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("button", { className: "btn btn-secondary gf-form-btn", onClick: onReset }, "reset"))) : (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("input", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ type: "password", className: "gf-form-input width-" + inputWidth, placeholder: placeholder }, inputProps))) }));
};
SecretFormField.defaultProps = defaultProps;
SecretFormField.displayName = 'SecretFormField';


/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/ButtonSelect.tsx":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/ButtonSelect.tsx ***!
  \********************************************************************/
/*! exports provided: ButtonSelect */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ButtonSelect", function() { return ButtonSelect; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Select */ "./packages/grafana-ui/src/components/Select/Select.tsx");



var ButtonComponent = function (buttonProps) { return function (props) {
    var label = buttonProps.label, className = buttonProps.className, iconClass = buttonProps.iconClass;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: props.innerRef, className: "btn navbar-button navbar-button--tight " + className, onClick: props.selectProps.menuIsOpen ? props.selectProps.onMenuClose : props.selectProps.onMenuOpen, onBlur: props.selectProps.onMenuClose, tabIndex: 0 },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "select-button" },
            iconClass && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "select-button-icon " + iconClass }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "select-button-value" }, label ? label : ''),
            !props.menuIsOpen && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-down fa-fw" }),
            props.menuIsOpen && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-up fa-fw" }))));
}; };
var ButtonSelect = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ButtonSelect, _super);
    function ButtonSelect() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (item) {
            var onChange = _this.props.onChange;
            onChange(item);
        };
        return _this;
    }
    ButtonSelect.prototype.render = function () {
        var _a = this.props, className = _a.className, options = _a.options, value = _a.value, label = _a.label, iconClass = _a.iconClass, components = _a.components, maxMenuHeight = _a.maxMenuHeight, tooltipContent = _a.tooltipContent, isMenuOpen = _a.isMenuOpen, onOpenMenu = _a.onOpenMenu, onCloseMenu = _a.onCloseMenu, tabSelectsValue = _a.tabSelectsValue, _b = _a.autoFocus, autoFocus = _b === void 0 ? true : _b;
        var combinedComponents = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, components, { Control: ButtonComponent({ label: label, className: className, iconClass: iconClass }) });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Select__WEBPACK_IMPORTED_MODULE_2__["default"], { autoFocus: autoFocus, backspaceRemovesValue: false, isClearable: false, isSearchable: false, options: options, onChange: this.onChange, value: value, isOpen: isMenuOpen, onOpenMenu: onOpenMenu, onCloseMenu: onCloseMenu, maxMenuHeight: maxMenuHeight, components: combinedComponents, className: "gf-form-select-box-button-select", tooltipContent: tooltipContent, tabSelectsValue: tabSelectsValue }));
    };
    return ButtonSelect;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/IndicatorsContainer.tsx":
/*!***************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/IndicatorsContainer.tsx ***!
  \***************************************************************************/
/*! exports provided: IndicatorsContainer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IndicatorsContainer", function() { return IndicatorsContainer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @torkelo/react-select */ "./node_modules/@torkelo/react-select/dist/react-select.esm.js");


// Ignoring because I couldn't get @types/react-select work wih Torkel's fork
// @ts-ignore

var IndicatorsContainer = function (props) {
    var isOpen = props.selectProps.menuIsOpen;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__["components"].IndicatorsContainer, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-select-box__select-arrow " + (isOpen ? "gf-form-select-box__select-arrow--reversed" : '') })));
};
/* harmony default export */ __webpack_exports__["default"] = (IndicatorsContainer);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/NoOptionsMessage.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/NoOptionsMessage.tsx ***!
  \************************************************************************/
/*! exports provided: NoOptionsMessage, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoOptionsMessage", function() { return NoOptionsMessage; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @torkelo/react-select */ "./node_modules/@torkelo/react-select/dist/react-select.esm.js");


// Ignoring because I couldn't get @types/react-select work wih Torkel's fork
// @ts-ignore

var NoOptionsMessage = function (props) {
    var children = props.children;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__["components"].Option, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__desc-option" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__desc-option__body" }, children))));
};
/* harmony default export */ __webpack_exports__["default"] = (NoOptionsMessage);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/Select.tsx":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/Select.tsx ***!
  \**************************************************************/
/*! exports provided: MenuList, Select, AsyncSelect, WrapInTooltip, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MenuList", function() { return MenuList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Select", function() { return Select; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AsyncSelect", function() { return AsyncSelect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WrapInTooltip", function() { return WrapInTooltip; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _torkelo_react_select__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @torkelo/react-select */ "./node_modules/@torkelo/react-select/dist/react-select.esm.js");
/* harmony import */ var _torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @torkelo/react-select/lib/Async */ "./node_modules/@torkelo/react-select/lib/Async.js");
/* harmony import */ var _torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _SelectOption__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SelectOption */ "./packages/grafana-ui/src/components/Select/SelectOption.tsx");
/* harmony import */ var _SelectOptionGroup__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SelectOptionGroup */ "./packages/grafana-ui/src/components/Select/SelectOptionGroup.tsx");
/* harmony import */ var _IndicatorsContainer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./IndicatorsContainer */ "./packages/grafana-ui/src/components/Select/IndicatorsContainer.tsx");
/* harmony import */ var _NoOptionsMessage__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./NoOptionsMessage */ "./packages/grafana-ui/src/components/Select/NoOptionsMessage.tsx");
/* harmony import */ var _resetSelectStyles__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./resetSelectStyles */ "./packages/grafana-ui/src/components/Select/resetSelectStyles.ts");
/* harmony import */ var _CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../CustomScrollbar/CustomScrollbar */ "./packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx");
/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");

// Libraries


// Ignoring because I couldn't get @types/react-select work wih Torkel's fork
// @ts-ignore

// @ts-ignore

// @ts-ignore

// Components







var MenuList = function (props) {
    return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_3__["components"].MenuList, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
        react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_10__["CustomScrollbar"], { autoHide: false, autoHeightMax: "inherit" }, props.children)));
};
var Select = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Select, _super);
    function Select() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Select.prototype.render = function () {
        var _a = this.props, defaultValue = _a.defaultValue, getOptionLabel = _a.getOptionLabel, getOptionValue = _a.getOptionValue, onChange = _a.onChange, options = _a.options, placeholder = _a.placeholder, width = _a.width, value = _a.value, className = _a.className, isDisabled = _a.isDisabled, isLoading = _a.isLoading, isSearchable = _a.isSearchable, isClearable = _a.isClearable, backspaceRemovesValue = _a.backspaceRemovesValue, isMulti = _a.isMulti, autoFocus = _a.autoFocus, openMenuOnFocus = _a.openMenuOnFocus, onBlur = _a.onBlur, maxMenuHeight = _a.maxMenuHeight, noOptionsMessage = _a.noOptionsMessage, isOpen = _a.isOpen, components = _a.components, tooltipContent = _a.tooltipContent, tabSelectsValue = _a.tabSelectsValue, onCloseMenu = _a.onCloseMenu, onOpenMenu = _a.onOpenMenu;
        var widthClass = '';
        if (width) {
            widthClass = 'width-' + width;
        }
        var selectClassNames = classnames__WEBPACK_IMPORTED_MODULE_1___default()('gf-form-input', 'gf-form-input--form-dropdown', widthClass, className);
        var selectComponents = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, Select.defaultProps.components, components);
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(WrapInTooltip, { onCloseMenu: onCloseMenu, onOpenMenu: onOpenMenu, tooltipContent: tooltipContent, isOpen: isOpen }, function (onOpenMenuInternal, onCloseMenuInternal) {
            return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_3__["default"], { classNamePrefix: "gf-form-select-box", className: selectClassNames, components: selectComponents, defaultValue: defaultValue, value: value, getOptionLabel: getOptionLabel, getOptionValue: getOptionValue, menuShouldScrollIntoView: false, isSearchable: isSearchable, onChange: onChange, options: options, placeholder: placeholder || 'Choose', styles: Object(_resetSelectStyles__WEBPACK_IMPORTED_MODULE_9__["default"])(), isDisabled: isDisabled, isLoading: isLoading, isClearable: isClearable, autoFocus: autoFocus, onBlur: onBlur, openMenuOnFocus: openMenuOnFocus, maxMenuHeight: maxMenuHeight, noOptionsMessage: noOptionsMessage, isMulti: isMulti, backspaceRemovesValue: backspaceRemovesValue, menuIsOpen: isOpen, onMenuOpen: onOpenMenuInternal, onMenuClose: onCloseMenuInternal, tabSelectsValue: tabSelectsValue }));
        }));
    };
    Select.defaultProps = {
        className: '',
        isDisabled: false,
        isSearchable: true,
        isClearable: false,
        isMulti: false,
        openMenuOnFocus: false,
        autoFocus: false,
        isLoading: false,
        backspaceRemovesValue: true,
        maxMenuHeight: 300,
        tabSelectsValue: true,
        components: {
            Option: _SelectOption__WEBPACK_IMPORTED_MODULE_5__["SelectOption"],
            SingleValue: _SelectOption__WEBPACK_IMPORTED_MODULE_5__["SingleValue"],
            IndicatorsContainer: _IndicatorsContainer__WEBPACK_IMPORTED_MODULE_7__["default"],
            MenuList: MenuList,
            Group: _SelectOptionGroup__WEBPACK_IMPORTED_MODULE_6__["default"],
        },
    };
    return Select;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));

var AsyncSelect = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AsyncSelect, _super);
    function AsyncSelect() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AsyncSelect.prototype.render = function () {
        var _a = this.props, defaultValue = _a.defaultValue, getOptionLabel = _a.getOptionLabel, getOptionValue = _a.getOptionValue, onChange = _a.onChange, placeholder = _a.placeholder, width = _a.width, value = _a.value, className = _a.className, loadOptions = _a.loadOptions, defaultOptions = _a.defaultOptions, isLoading = _a.isLoading, loadingMessage = _a.loadingMessage, noOptionsMessage = _a.noOptionsMessage, isDisabled = _a.isDisabled, isSearchable = _a.isSearchable, isClearable = _a.isClearable, backspaceRemovesValue = _a.backspaceRemovesValue, autoFocus = _a.autoFocus, onBlur = _a.onBlur, openMenuOnFocus = _a.openMenuOnFocus, maxMenuHeight = _a.maxMenuHeight, isMulti = _a.isMulti, tooltipContent = _a.tooltipContent, onCloseMenu = _a.onCloseMenu, onOpenMenu = _a.onOpenMenu, isOpen = _a.isOpen;
        var widthClass = '';
        if (width) {
            widthClass = 'width-' + width;
        }
        var selectClassNames = classnames__WEBPACK_IMPORTED_MODULE_1___default()('gf-form-input', 'gf-form-input--form-dropdown', widthClass, className);
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(WrapInTooltip, { onCloseMenu: onCloseMenu, onOpenMenu: onOpenMenu, tooltipContent: tooltipContent, isOpen: isOpen }, function (onOpenMenuInternal, onCloseMenuInternal) {
            return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_4___default.a, { classNamePrefix: "gf-form-select-box", className: selectClassNames, components: {
                    Option: _SelectOption__WEBPACK_IMPORTED_MODULE_5__["SelectOption"],
                    SingleValue: _SelectOption__WEBPACK_IMPORTED_MODULE_5__["SingleValue"],
                    IndicatorsContainer: _IndicatorsContainer__WEBPACK_IMPORTED_MODULE_7__["default"],
                    NoOptionsMessage: _NoOptionsMessage__WEBPACK_IMPORTED_MODULE_8__["default"],
                }, defaultValue: defaultValue, value: value, getOptionLabel: getOptionLabel, getOptionValue: getOptionValue, menuShouldScrollIntoView: false, onChange: onChange, loadOptions: loadOptions, isLoading: isLoading, defaultOptions: defaultOptions, placeholder: placeholder || 'Choose', styles: Object(_resetSelectStyles__WEBPACK_IMPORTED_MODULE_9__["default"])(), loadingMessage: loadingMessage, noOptionsMessage: noOptionsMessage, isDisabled: isDisabled, isSearchable: isSearchable, isClearable: isClearable, autoFocus: autoFocus, onBlur: onBlur, openMenuOnFocus: openMenuOnFocus, maxMenuHeight: maxMenuHeight, isMulti: isMulti, backspaceRemovesValue: backspaceRemovesValue }));
        }));
    };
    AsyncSelect.defaultProps = {
        className: '',
        components: {},
        loadingMessage: function () { return 'Loading...'; },
        isDisabled: false,
        isClearable: false,
        isMulti: false,
        isSearchable: true,
        backspaceRemovesValue: true,
        autoFocus: false,
        openMenuOnFocus: false,
        maxMenuHeight: 300,
    };
    return AsyncSelect;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));

var WrapInTooltip = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WrapInTooltip, _super);
    function WrapInTooltip() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isOpenInternal: false,
        };
        _this.onOpenMenu = function () {
            var onOpenMenu = _this.props.onOpenMenu;
            if (onOpenMenu) {
                onOpenMenu();
            }
            _this.setState({ isOpenInternal: true });
        };
        _this.onCloseMenu = function () {
            var onCloseMenu = _this.props.onCloseMenu;
            if (onCloseMenu) {
                onCloseMenu();
            }
            _this.setState({ isOpenInternal: false });
        };
        return _this;
    }
    WrapInTooltip.prototype.render = function () {
        var _a = this.props, children = _a.children, isOpen = _a.isOpen, tooltipContent = _a.tooltipContent;
        var isOpenInternal = this.state.isOpenInternal;
        var showTooltip = undefined;
        if (isOpenInternal || isOpen) {
            showTooltip = false;
        }
        if (tooltipContent) {
            return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_11__["Tooltip"], { show: showTooltip, content: tooltipContent, placement: "bottom" },
                react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", null, children(this.onOpenMenu, this.onCloseMenu))));
        }
        else {
            return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", null, children(this.onOpenMenu, this.onCloseMenu));
        }
    };
    return WrapInTooltip;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (Select);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/SelectOption.tsx":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/SelectOption.tsx ***!
  \********************************************************************/
/*! exports provided: SelectOption, SingleValue, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectOption", function() { return SelectOption; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SingleValue", function() { return SingleValue; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @torkelo/react-select */ "./node_modules/@torkelo/react-select/dist/react-select.esm.js");


// Ignoring because I couldn't get @types/react-select work wih Torkel's fork
// @ts-ignore

var SelectOption = function (props) {
    var children = props.children, isSelected = props.isSelected, data = props.data;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__["components"].Option, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__desc-option" },
            data.imgUrl && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { className: "gf-form-select-box__desc-option__img", src: data.imgUrl }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__desc-option__body" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, children),
                data.description && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__desc-option__desc" }, data.description)),
            isSelected && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-check", "aria-hidden": "true" }))));
};
// was not able to type this without typescript error
var SingleValue = function (props) {
    var children = props.children, data = props.data;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__["components"].SingleValue, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__img-value" },
            data.imgUrl && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { className: "gf-form-select-box__desc-option__img", src: data.imgUrl }),
            children)));
};
/* harmony default export */ __webpack_exports__["default"] = (SelectOption);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/SelectOptionGroup.tsx":
/*!*************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/SelectOptionGroup.tsx ***!
  \*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);


var SelectOptionGroup = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SelectOptionGroup, _super);
    function SelectOptionGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            expanded: false,
        };
        _this.onToggleChildren = function () {
            _this.setState(function (prevState) { return ({
                expanded: !prevState.expanded,
            }); });
        };
        return _this;
    }
    SelectOptionGroup.prototype.componentDidMount = function () {
        if (this.props.data.expanded) {
            this.setState({ expanded: true });
        }
        else if (this.props.selectProps && this.props.selectProps.value) {
            var value_1 = this.props.selectProps.value.value;
            if (value_1 && this.props.options.some(function (option) { return option.value === value_1; })) {
                this.setState({ expanded: true });
            }
        }
    };
    SelectOptionGroup.prototype.componentDidUpdate = function (nextProps) {
        if (nextProps.selectProps.inputValue !== '') {
            this.setState({ expanded: true });
        }
    };
    SelectOptionGroup.prototype.render = function () {
        var _a = this.props, children = _a.children, label = _a.label;
        var expanded = this.state.expanded;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__option-group" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-box__option-group__header", onClick: this.onToggleChildren },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "flex-grow-1" }, label),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa " + (expanded ? 'fa-caret-left' : 'fa-caret-down') }),
                ' '),
            expanded && children));
    };
    return SelectOptionGroup;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
/* harmony default export */ __webpack_exports__["default"] = (SelectOptionGroup);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Select/resetSelectStyles.ts":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Select/resetSelectStyles.ts ***!
  \************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return resetSelectStyles; });
function resetSelectStyles() {
    return {
        clearIndicator: function () { return ({}); },
        container: function () { return ({}); },
        control: function () { return ({}); },
        dropdownIndicator: function () { return ({}); },
        group: function () { return ({}); },
        groupHeading: function () { return ({}); },
        indicatorsContainer: function () { return ({}); },
        indicatorSeparator: function () { return ({}); },
        input: function () { return ({}); },
        loadingIndicator: function () { return ({}); },
        loadingMessage: function () { return ({}); },
        menu: function () { return ({}); },
        menuList: function (_a) {
            var maxHeight = _a.maxHeight;
            return ({
                maxHeight: maxHeight,
            });
        },
        multiValue: function () { return ({}); },
        multiValueLabel: function () { return ({}); },
        multiValueRemove: function () { return ({}); },
        noOptionsMessage: function () { return ({}); },
        option: function () { return ({}); },
        placeholder: function () { return ({}); },
        singleValue: function () { return ({}); },
        valueContainer: function () { return ({}); },
    };
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/SetInterval/SetInterval.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/SetInterval/SetInterval.tsx ***!
  \************************************************************************/
/*! exports provided: getIntervalFromString, SetInterval */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getIntervalFromString", function() { return getIntervalFromString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetInterval", function() { return SetInterval; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm5/index.js");
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm5/operators/index.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../RefreshPicker/RefreshPicker */ "./packages/grafana-ui/src/components/RefreshPicker/RefreshPicker.tsx");







function getIntervalFromString(strInterval) {
    return {
        label: strInterval,
        value: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["stringToMs"])(strInterval),
    };
}
var SetInterval = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetInterval, _super);
    function SetInterval(props) {
        var _this = _super.call(this, props) || this;
        _this.propsSubject = new rxjs__WEBPACK_IMPORTED_MODULE_2__["Subject"]();
        _this.subscription = null;
        return _this;
    }
    SetInterval.prototype.componentDidMount = function () {
        var _this = this;
        // Creating a subscription to propsSubject. This subject pushes values every time
        // SetInterval's props change
        this.subscription = this.propsSubject
            .pipe(
        // switchMap creates a new observables based on the input stream,
        // which becomes part of the propsSubject stream
        Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["switchMap"])(function (props) {
            // If the query is live, empty value is emited. `of` creates single value,
            // which is merged to propsSubject stream
            if (Object(_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_6__["isLive"])(props.interval)) {
                return Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["of"])({});
            }
            // When query is loading, a new stream is merged. But it's a stream that emits no values(NEVER),
            // hence next call of this function will happen when query changes, and new props are passed into this component
            // When query is NOT loading, a new value is emited, this time it's an interval value,
            // which makes tap function below execute on that interval basis.
            return props.loading ? rxjs__WEBPACK_IMPORTED_MODULE_2__["NEVER"] : Object(rxjs__WEBPACK_IMPORTED_MODULE_2__["interval"])(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["stringToMs"])(props.interval));
        }), 
        // tap will execute function passed via func prop
        // * on value from `of` stream merged if query is live
        // * on specified interval (triggered by values emited by interval)
        Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["tap"])(function () { return _this.props.func(); }))
            .subscribe();
        // When component has mounted, propsSubject emits it's first value
        this.propsSubject.next(this.props);
    };
    SetInterval.prototype.componentDidUpdate = function (prevProps) {
        if ((Object(_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_6__["isLive"])(prevProps.interval) && Object(_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_6__["isLive"])(this.props.interval)) || lodash__WEBPACK_IMPORTED_MODULE_4___default.a.isEqual(prevProps, this.props)) {
            return;
        }
        // if props changed, a new value is emited from propsSubject
        this.propsSubject.next(this.props);
    };
    SetInterval.prototype.componentWillUnmount = function () {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
        this.propsSubject.unsubscribe();
    };
    SetInterval.prototype.render = function () {
        return null;
    };
    return SetInterval;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/SingleStatShared/FieldDisplayEditor.tsx":
/*!************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/SingleStatShared/FieldDisplayEditor.tsx ***!
  \************************************************************************************/
/*! exports provided: FieldDisplayEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FieldDisplayEditor", function() { return FieldDisplayEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../FormLabel/FormLabel */ "./packages/grafana-ui/src/components/FormLabel/FormLabel.tsx");
/* harmony import */ var _FormField_FormField__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../FormField/FormField */ "./packages/grafana-ui/src/components/FormField/FormField.tsx");
/* harmony import */ var _StatsPicker_StatsPicker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../StatsPicker/StatsPicker */ "./packages/grafana-ui/src/components/StatsPicker/StatsPicker.tsx");
/* harmony import */ var _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils/fieldDisplay */ "./packages/grafana-ui/src/utils/fieldDisplay.ts");
/* harmony import */ var _Select_Select__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Select/Select */ "./packages/grafana-ui/src/components/Select/Select.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libraries

// Components



// Types



var showOptions = [
    {
        value: true,
        label: 'All Values',
        description: 'Each row in the response data',
    },
    {
        value: false,
        label: 'Calculation',
        description: 'Calculate a value based on the response',
    },
];
var FieldDisplayEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FieldDisplayEditor, _super);
    function FieldDisplayEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onShowValuesChange = function (item) {
            var val = item.value === true;
            _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.value, { values: val }));
        };
        _this.onCalcsChange = function (calcs) {
            _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.value, { calcs: calcs }));
        };
        _this.onDefaultsChange = function (value) {
            _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.value, { defaults: value }));
        };
        _this.onLimitChange = function (event) {
            _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.value, { limit: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_7__["toIntegerOrUndefined"])(event.target.value) }));
        };
        return _this;
    }
    FieldDisplayEditor.prototype.render = function () {
        var value = this.props.value;
        var calcs = value.calcs, values = value.values, limit = value.limit;
        var labelWidth = this.props.labelWidth || 5;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Show"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Select_Select__WEBPACK_IMPORTED_MODULE_6__["default"], { options: showOptions, value: values ? showOptions[0] : showOptions[1], onChange: this.onShowValuesChange })),
            values ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormField_FormField__WEBPACK_IMPORTED_MODULE_3__["FormField"], { label: "Limit", labelWidth: labelWidth, placeholder: "" + _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_5__["DEFAULT_FIELD_DISPLAY_VALUES_LIMIT"], onChange: this.onLimitChange, value: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_7__["toNumberString"])(limit), type: "number" })) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Calc"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_StatsPicker_StatsPicker__WEBPACK_IMPORTED_MODULE_4__["StatsPicker"], { width: 12, placeholder: "Choose Stat", defaultStat: _grafana_data__WEBPACK_IMPORTED_MODULE_7__["ReducerID"].mean, allowMultiple: false, stats: calcs, onChange: this.onCalcsChange })))));
    };
    return FieldDisplayEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/SingleStatShared/FieldPropertiesEditor.tsx":
/*!***************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/SingleStatShared/FieldPropertiesEditor.tsx ***!
  \***************************************************************************************/
/*! exports provided: FieldPropertiesEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FieldPropertiesEditor", function() { return FieldPropertiesEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _FormField_FormField__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../FormField/FormField */ "./packages/grafana-ui/src/components/FormField/FormField.tsx");
/* harmony import */ var _FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../FormLabel/FormLabel */ "./packages/grafana-ui/src/components/FormLabel/FormLabel.tsx");
/* harmony import */ var _UnitPicker_UnitPicker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../UnitPicker/UnitPicker */ "./packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utils/fieldDisplay */ "./packages/grafana-ui/src/utils/fieldDisplay.ts");

// Libraries

// Components



// Types


var labelWidth = 6;
var FieldPropertiesEditor = function (_a) {
    var value = _a.value, onChange = _a.onChange, showMinMax = _a.showMinMax;
    var unit = value.unit, title = value.title;
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(value.decimals !== undefined && value.decimals !== null ? value.decimals.toString() : ''), 2), decimals = _b[0], setDecimals = _b[1];
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["toNumberString"])(value.min)), 2), min = _c[0], setMin = _c[1];
    var _d = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["toNumberString"])(value.max)), 2), max = _d[0], setMax = _d[1];
    var onTitleChange = function (event) {
        onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, value, { title: event.target.value }));
    };
    var onDecimalChange = Object(react__WEBPACK_IMPORTED_MODULE_1__["useCallback"])(function (event) {
        setDecimals(event.target.value);
    }, [value.decimals, onChange]);
    var onMinChange = Object(react__WEBPACK_IMPORTED_MODULE_1__["useCallback"])(function (event) {
        setMin(event.target.value);
    }, [value.min, onChange]);
    var onMaxChange = Object(react__WEBPACK_IMPORTED_MODULE_1__["useCallback"])(function (event) {
        setMax(event.target.value);
    }, [value.max, onChange]);
    var onUnitChange = function (unit) {
        onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, value, { unit: unit.value }));
    };
    var commitChanges = Object(react__WEBPACK_IMPORTED_MODULE_1__["useCallback"])(function () {
        onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, value, { decimals: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["toIntegerOrUndefined"])(decimals), min: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["toFloatOrUndefined"])(min), max: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["toFloatOrUndefined"])(max) }));
    }, [min, max, decimals]);
    var titleTooltip = (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
        "Template Variables:",
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
        '${' + _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_6__["VAR_SERIES_NAME"] + '}',
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
        '${' + _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_6__["VAR_FIELD_NAME"] + '}',
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
        '$' + _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_6__["VAR_CELL_PREFIX"] + '{N}',
        " / ",
        '$' + _utils_fieldDisplay__WEBPACK_IMPORTED_MODULE_6__["VAR_CALC"]));
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormField_FormField__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Title", labelWidth: labelWidth, onChange: onTitleChange, value: title, tooltip: titleTooltip, placeholder: "Auto" }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_3__["FormLabel"], { width: labelWidth }, "Unit"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_UnitPicker_UnitPicker__WEBPACK_IMPORTED_MODULE_4__["UnitPicker"], { defaultValue: unit, onChange: onUnitChange })),
        showMinMax && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormField_FormField__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Min", labelWidth: labelWidth, onChange: onMinChange, onBlur: commitChanges, value: min, type: "number" }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormField_FormField__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Max", labelWidth: labelWidth, onChange: onMaxChange, onBlur: commitChanges, value: max, type: "number" }))),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FormField_FormField__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Decimals", labelWidth: labelWidth, placeholder: "auto", onChange: onDecimalChange, onBlur: commitChanges, value: decimals, type: "number" })));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/SingleStatShared/SingleStatBaseOptions.ts":
/*!**************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/SingleStatShared/SingleStatBaseOptions.ts ***!
  \**************************************************************************************/
/*! exports provided: sharedSingleStatPanelChangedHandler, sharedSingleStatMigrationHandler, moveThresholdsAndMappingsToField, migrateFromValueOptions, migrateOldThresholds, convertOldAngulrValueMapping */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatPanelChangedHandler", function() { return sharedSingleStatPanelChangedHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatMigrationHandler", function() { return sharedSingleStatMigrationHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moveThresholdsAndMappingsToField", function() { return moveThresholdsAndMappingsToField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "migrateFromValueOptions", function() { return migrateFromValueOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "migrateOldThresholds", function() { return migrateOldThresholds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertOldAngulrValueMapping", function() { return convertOldAngulrValueMapping; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_cloneDeep__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/cloneDeep */ "./node_modules/lodash/cloneDeep.js");
/* harmony import */ var lodash_cloneDeep__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_cloneDeep__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_omit__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/omit */ "./node_modules/lodash/omit.js");
/* harmony import */ var lodash_omit__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_omit__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _types_panel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../types/panel */ "./packages/grafana-ui/src/types/panel.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");





var optionsToKeep = ['fieldOptions', 'orientation'];
function sharedSingleStatPanelChangedHandler(options, prevPluginId, prevOptions) {
    var e_1, _a, e_2, _b;
    // Migrating from angular singlestat
    if (prevPluginId === 'singlestat' && prevOptions.angular) {
        var panel = prevOptions.angular;
        var reducer = _grafana_data__WEBPACK_IMPORTED_MODULE_4__["fieldReducers"].getIfExists(panel.valueName);
        var options_1 = {
            fieldOptions: {
                defaults: {},
                override: {},
                calcs: [reducer ? reducer.id : _grafana_data__WEBPACK_IMPORTED_MODULE_4__["ReducerID"].mean],
            },
            orientation: _types_panel__WEBPACK_IMPORTED_MODULE_3__["VizOrientation"].Horizontal,
        };
        var defaults = options_1.fieldOptions.defaults;
        if (panel.format) {
            defaults.unit = panel.format;
        }
        if (panel.nullPointMode) {
            defaults.nullValueMode = panel.nullPointMode;
        }
        if (panel.nullText) {
            defaults.noValue = panel.nullText;
        }
        if (panel.decimals || panel.decimals === 0) {
            defaults.decimals = panel.decimals;
        }
        // Convert thresholds and color values
        if (panel.thresholds && panel.colors) {
            var levels = panel.thresholds.split(',').map(function (strVale) {
                return Number(strVale.trim());
            });
            // One more color than threshold
            var thresholds = [];
            try {
                for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.colors), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var color = _d.value;
                    var idx = thresholds.length - 1;
                    if (idx >= 0) {
                        thresholds.push({ value: levels[idx], color: color });
                    }
                    else {
                        thresholds.push({ value: -Infinity, color: color });
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
                }
                finally { if (e_1) throw e_1.error; }
            }
            defaults.thresholds = thresholds;
        }
        // Convert value mappings
        var mappings = convertOldAngulrValueMapping(panel);
        if (mappings && mappings.length) {
            defaults.mappings = mappings;
        }
        if (panel.gauge) {
            defaults.min = panel.gauge.minValue;
            defaults.max = panel.gauge.maxValue;
        }
        return options_1;
    }
    try {
        for (var optionsToKeep_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](optionsToKeep), optionsToKeep_1_1 = optionsToKeep_1.next(); !optionsToKeep_1_1.done; optionsToKeep_1_1 = optionsToKeep_1.next()) {
            var k = optionsToKeep_1_1.value;
            if (prevOptions.hasOwnProperty(k)) {
                options[k] = lodash_cloneDeep__WEBPACK_IMPORTED_MODULE_1___default()(prevOptions[k]);
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (optionsToKeep_1_1 && !optionsToKeep_1_1.done && (_b = optionsToKeep_1.return)) _b.call(optionsToKeep_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return options;
}
function sharedSingleStatMigrationHandler(panel) {
    if (!panel.options) {
        // This happens on the first load or when migrating from angular
        return {};
    }
    var previousVersion = parseFloat(panel.pluginVersion || '6.1');
    var options = panel.options;
    if (previousVersion < 6.2) {
        options = migrateFromValueOptions(options);
    }
    if (previousVersion < 6.3) {
        options = moveThresholdsAndMappingsToField(options);
    }
    return options;
}
function moveThresholdsAndMappingsToField(old) {
    var fieldOptions = old.fieldOptions;
    if (!fieldOptions) {
        return old;
    }
    var _a = old.fieldOptions, mappings = _a.mappings, thresholds = _a.thresholds, rest = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["mappings", "thresholds"]);
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, old, { fieldOptions: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, rest, { defaults: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, fieldOptions.defaults, { mappings: mappings, thresholds: migrateOldThresholds(thresholds) }) }) });
}
/*
 * Moves valueMappings and thresholds from root to new fieldOptions object
 * Renames valueOptions to to defaults and moves it under fieldOptions
 */
function migrateFromValueOptions(old) {
    var valueOptions = old.valueOptions;
    if (!valueOptions) {
        return old;
    }
    var fieldOptions = {};
    var fieldDefaults = {};
    fieldOptions.mappings = old.valueMappings;
    fieldOptions.thresholds = old.thresholds;
    fieldOptions.defaults = fieldDefaults;
    fieldDefaults.unit = valueOptions.unit;
    fieldDefaults.decimals = valueOptions.decimals;
    // Make sure the stats have a valid name
    if (valueOptions.stat) {
        var reducer = _grafana_data__WEBPACK_IMPORTED_MODULE_4__["fieldReducers"].get(valueOptions.stat);
        if (reducer) {
            fieldOptions.calcs = [reducer.id];
        }
    }
    fieldDefaults.min = old.minValue;
    fieldDefaults.max = old.maxValue;
    var newOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, old, { fieldOptions: fieldOptions });
    return lodash_omit__WEBPACK_IMPORTED_MODULE_2___default()(newOptions, 'valueMappings', 'thresholds', 'valueOptions', 'minValue', 'maxValue');
}
function migrateOldThresholds(thresholds) {
    if (!thresholds || !thresholds.length) {
        return undefined;
    }
    var copy = thresholds.map(function (t) {
        return {
            // Drops 'index'
            value: t.value === null ? -Infinity : t.value,
            color: t.color,
        };
    });
    Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["sortThresholds"])(copy);
    copy[0].value = -Infinity;
    return copy;
}
/**
 * Convert the angular single stat mapping to new react style
 */
function convertOldAngulrValueMapping(panel) {
    var mappings = [];
    // Guess the right type based on options
    var mappingType = panel.mappingType;
    if (!panel.mappingType) {
        if (panel.valueMaps && panel.valueMaps.length) {
            mappingType = 1;
        }
        else if (panel.rangeMaps && panel.rangeMaps.length) {
            mappingType = 2;
        }
    }
    // check value to text mappings if its enabled
    if (mappingType === 1) {
        for (var i = 0; i < panel.valueMaps.length; i++) {
            var map = panel.valueMaps[i];
            mappings.push(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, map, { id: i, type: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["MappingType"].ValueToText }));
        }
    }
    else if (mappingType === 2) {
        for (var i = 0; i < panel.rangeMaps.length; i++) {
            var map = panel.rangeMaps[i];
            mappings.push(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, map, { id: i, type: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["MappingType"].RangeToText }));
        }
    }
    return mappings;
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/SingleStatShared/index.ts":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/SingleStatShared/index.ts ***!
  \**********************************************************************/
/*! exports provided: FieldDisplayEditor, FieldPropertiesEditor, SingleStatBaseOptions, sharedSingleStatPanelChangedHandler, sharedSingleStatMigrationHandler, convertOldAngulrValueMapping */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _FieldDisplayEditor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./FieldDisplayEditor */ "./packages/grafana-ui/src/components/SingleStatShared/FieldDisplayEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldDisplayEditor", function() { return _FieldDisplayEditor__WEBPACK_IMPORTED_MODULE_0__["FieldDisplayEditor"]; });

/* harmony import */ var _FieldPropertiesEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./FieldPropertiesEditor */ "./packages/grafana-ui/src/components/SingleStatShared/FieldPropertiesEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldPropertiesEditor", function() { return _FieldPropertiesEditor__WEBPACK_IMPORTED_MODULE_1__["FieldPropertiesEditor"]; });

/* harmony import */ var _SingleStatBaseOptions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SingleStatBaseOptions */ "./packages/grafana-ui/src/components/SingleStatShared/SingleStatBaseOptions.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SingleStatBaseOptions", function() { return _SingleStatBaseOptions__WEBPACK_IMPORTED_MODULE_2__["SingleStatBaseOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatPanelChangedHandler", function() { return _SingleStatBaseOptions__WEBPACK_IMPORTED_MODULE_2__["sharedSingleStatPanelChangedHandler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatMigrationHandler", function() { return _SingleStatBaseOptions__WEBPACK_IMPORTED_MODULE_2__["sharedSingleStatMigrationHandler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "convertOldAngulrValueMapping", function() { return _SingleStatBaseOptions__WEBPACK_IMPORTED_MODULE_2__["convertOldAngulrValueMapping"]; });






/***/ }),

/***/ "./packages/grafana-ui/src/components/StatsPicker/StatsPicker.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/StatsPicker/StatsPicker.tsx ***!
  \************************************************************************/
/*! exports provided: StatsPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StatsPicker", function() { return StatsPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/isArray */ "./node_modules/lodash/isArray.js");
/* harmony import */ var lodash_isArray__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_isArray__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_difference__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/difference */ "./node_modules/lodash/difference.js");
/* harmony import */ var lodash_difference__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_difference__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");






var StatsPicker = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StatsPicker, _super);
    function StatsPicker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.checkInput = function () {
            var _a = _this.props, stats = _a.stats, allowMultiple = _a.allowMultiple, defaultStat = _a.defaultStat, onChange = _a.onChange;
            var current = _grafana_data__WEBPACK_IMPORTED_MODULE_5__["fieldReducers"].list(stats);
            if (current.length !== stats.length) {
                var found = current.map(function (v) { return v.id; });
                var notFound = lodash_difference__WEBPACK_IMPORTED_MODULE_3___default()(stats, found);
                console.warn('Unknown stats', notFound, stats);
                onChange(current.map(function (stat) { return stat.id; }));
            }
            // Make sure there is only one
            if (!allowMultiple && stats.length > 1) {
                console.warn('Removing extra stat', stats);
                onChange([stats[0]]);
            }
            // Set the reducer from callback
            if (defaultStat && stats.length < 1) {
                onChange([defaultStat]);
            }
        };
        _this.onSelectionChange = function (item) {
            var onChange = _this.props.onChange;
            if (lodash_isArray__WEBPACK_IMPORTED_MODULE_2___default()(item)) {
                onChange(item.map(function (v) { return v.value; }));
            }
            else {
                onChange(item.value ? [item.value] : []);
            }
        };
        return _this;
    }
    StatsPicker.prototype.componentDidMount = function () {
        this.checkInput();
    };
    StatsPicker.prototype.componentDidUpdate = function (prevProps) {
        this.checkInput();
    };
    StatsPicker.prototype.render = function () {
        var _a = this.props, width = _a.width, stats = _a.stats, allowMultiple = _a.allowMultiple, defaultStat = _a.defaultStat, placeholder = _a.placeholder;
        var select = _grafana_data__WEBPACK_IMPORTED_MODULE_5__["fieldReducers"].selectOptions(stats);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_4__["Select"], { width: width, value: select.current, isClearable: !defaultStat, isMulti: allowMultiple, isSearchable: true, options: select.options, placeholder: placeholder, onChange: this.onSelectionChange }));
    };
    StatsPicker.defaultProps = {
        width: 12,
        allowMultiple: false,
    };
    return StatsPicker;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Switch/Switch.tsx":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Switch/Switch.tsx ***!
  \**************************************************************/
/*! exports provided: Switch */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Switch", function() { return Switch; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_uniqueId__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/uniqueId */ "./node_modules/lodash/uniqueId.js");
/* harmony import */ var lodash_uniqueId__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_uniqueId__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");




var Switch = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Switch, _super);
    function Switch() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            id: lodash_uniqueId__WEBPACK_IMPORTED_MODULE_2___default()(),
        };
        _this.internalOnChange = function (event) {
            event.stopPropagation();
            _this.props.onChange(event);
        };
        return _this;
    }
    Switch.prototype.render = function () {
        var _a = this.props, _b = _a.labelClass, labelClass = _b === void 0 ? '' : _b, _c = _a.switchClass, switchClass = _c === void 0 ? '' : _c, label = _a.label, checked = _a.checked, transparent = _a.transparent, className = _a.className, tooltip = _a.tooltip, tooltipPlacement = _a.tooltipPlacement;
        var labelId = this.state.id;
        var labelClassName = "gf-form-label " + labelClass + " " + (transparent ? 'gf-form-label--transparent' : '') + " pointer";
        var switchClassName = "gf-form-switch " + switchClass + " " + (transparent ? 'gf-form-switch--transparent' : '');
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-switch-container-react" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { htmlFor: labelId, className: "gf-form gf-form-switch-container " + (className || '') },
                label && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: labelClassName },
                    label,
                    tooltip && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_3__["Tooltip"], { placement: tooltipPlacement ? tooltipPlacement : 'auto', content: tooltip, theme: 'info' },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-help-icon gf-form-help-icon--right-normal" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-info-circle" })))))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: switchClassName },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", { id: labelId, type: "checkbox", checked: checked, onChange: this.internalOnChange }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-switch__slider" })))));
    };
    return Switch;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Table/Table.tsx":
/*!************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Table/Table.tsx ***!
  \************************************************************/
/*! exports provided: Table, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Table", function() { return Table; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_virtualized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-virtualized */ "./node_modules/react-virtualized/dist/es/index.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _TableCellBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./TableCellBuilder */ "./packages/grafana-ui/src/components/Table/TableCellBuilder.tsx");





var Table = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Table, _super);
    function Table(props) {
        var _this = _super.call(this, props) || this;
        _this.scrollToTop = false;
        _this.rotateWidth = 100;
        //----------------------------------------------------------------------
        //----------------------------------------------------------------------
        _this.doSort = function (columnIndex) {
            var sort = _this.state.sortBy;
            var dir = _this.state.sortDirection;
            if (sort !== columnIndex) {
                dir = 'DESC';
                sort = columnIndex;
            }
            else if (dir === 'DESC') {
                dir = 'ASC';
            }
            else {
                sort = null;
            }
            _this.setState({ sortBy: sort, sortDirection: dir });
        };
        /** Converts the grid coordinates to DataFrame coordinates */
        _this.getCellRef = function (rowIndex, columnIndex) {
            var _a = _this.props, showHeader = _a.showHeader, rotate = _a.rotate;
            var rowOffset = showHeader ? -1 : 0;
            if (rotate) {
                return { column: rowIndex, row: columnIndex + rowOffset };
            }
            else {
                return { column: columnIndex, row: rowIndex + rowOffset };
            }
        };
        _this.onCellClick = function (rowIndex, columnIndex) {
            var _a = _this.getCellRef(rowIndex, columnIndex), row = _a.row, column = _a.column;
            if (row < 0) {
                _this.doSort(column);
            }
            else {
                var field = _this.state.data.fields[columnIndex];
                var value = field.values.get(rowIndex);
                console.log('CLICK', value, field.name);
            }
        };
        _this.headerBuilder = function (cell) {
            var _a = _this.state, data = _a.data, sortBy = _a.sortBy, sortDirection = _a.sortDirection;
            var _b = cell.props, columnIndex = _b.columnIndex, rowIndex = _b.rowIndex, style = _b.style;
            var column = _this.getCellRef(rowIndex, columnIndex).column;
            var col = data.fields[column];
            var sorting = sortBy === column;
            if (!col) {
                col = {
                    name: '??' + columnIndex + '???',
                    config: {},
                    values: new _grafana_data__WEBPACK_IMPORTED_MODULE_3__["ArrayVector"](),
                    type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["FieldType"].other,
                };
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-table-header", style: style, onClick: function () { return _this.onCellClick(rowIndex, columnIndex); } },
                col.name,
                sorting && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_virtualized__WEBPACK_IMPORTED_MODULE_2__["SortIndicator"], { sortDirection: sortDirection })));
        };
        _this.getTableCellBuilder = function (column) {
            var render = _this.renderer[column];
            if (render && render.builder) {
                return render.builder;
            }
            return _TableCellBuilder__WEBPACK_IMPORTED_MODULE_4__["simpleCellBuilder"]; // the default
        };
        _this.cellRenderer = function (props) {
            var rowIndex = props.rowIndex, columnIndex = props.columnIndex, key = props.key, parent = props.parent;
            var _a = _this.getCellRef(rowIndex, columnIndex), row = _a.row, column = _a.column;
            var data = _this.state.data;
            var isHeader = row < 0;
            var rowData = isHeader ? data.fields : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["getDataFrameRow"])(data, row); // TODO! improve
            var value = rowData ? rowData[column] : '';
            var builder = isHeader ? _this.headerBuilder : _this.getTableCellBuilder(column);
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_virtualized__WEBPACK_IMPORTED_MODULE_2__["CellMeasurer"], { cache: _this.measurer, columnIndex: columnIndex, key: key, parent: parent, rowIndex: rowIndex }, builder({
                value: value,
                row: rowData,
                column: data.fields[column],
                table: _this,
                props: props,
            })));
        };
        _this.getColumnWidth = function (col) {
            if (_this.props.rotate) {
                return _this.rotateWidth; // fixed for now
            }
            return _this.renderer[col.index].width;
        };
        _this.state = {
            data: props.data,
        };
        _this.renderer = _this.initColumns(props);
        _this.measurer = new react_virtualized__WEBPACK_IMPORTED_MODULE_2__["CellMeasurerCache"]({
            defaultHeight: 30,
            fixedWidth: true,
        });
        return _this;
    }
    Table.prototype.componentDidUpdate = function (prevProps, prevState) {
        var _a = this.props, data = _a.data, styles = _a.styles, showHeader = _a.showHeader, rotate = _a.rotate;
        var _b = this.state, sortBy = _b.sortBy, sortDirection = _b.sortDirection;
        var dataChanged = data !== prevProps.data;
        var configsChanged = showHeader !== prevProps.showHeader ||
            this.props.rotate !== prevProps.rotate ||
            this.props.fixedColumns !== prevProps.fixedColumns ||
            this.props.fixedHeader !== prevProps.fixedHeader;
        // Reset the size cache
        if (dataChanged || configsChanged) {
            this.measurer.clearAll();
        }
        // Update the renderer if options change
        // We only *need* do to this if the header values changes, but this does every data update
        if (dataChanged || styles !== prevProps.styles) {
            this.renderer = this.initColumns(this.props);
        }
        if (dataChanged || rotate !== prevProps.rotate) {
            var _c = this.props, width = _c.width, minColumnWidth = _c.minColumnWidth;
            this.rotateWidth = Math.max(width / data.length, minColumnWidth);
        }
        // Update the data when data or sort changes
        if (dataChanged || sortBy !== prevState.sortBy || sortDirection !== prevState.sortDirection) {
            this.scrollToTop = true;
            this.setState({ data: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["sortDataFrame"])(data, sortBy, sortDirection === 'DESC') });
        }
    };
    /** Given the configuration, setup how each column gets rendered */
    Table.prototype.initColumns = function (props) {
        var _this = this;
        var styles = props.styles, data = props.data, width = props.width, minColumnWidth = props.minColumnWidth;
        if (!data || !data.fields || !data.fields.length || !styles) {
            return [];
        }
        var columnWidth = Math.max(width / data.fields.length, minColumnWidth);
        return data.fields.map(function (col, index) {
            var title = col.name;
            var style = null; // ColumnStyle
            // Find the style based on the text
            for (var i = 0; i < styles.length; i++) {
                var s = styles[i];
                var regex = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["stringToJsRegex"])(s.pattern);
                if (title.match(regex)) {
                    style = s;
                    if (s.alias) {
                        title = title.replace(regex, s.alias);
                    }
                    break;
                }
            }
            return {
                header: title,
                width: columnWidth,
                builder: Object(_TableCellBuilder__WEBPACK_IMPORTED_MODULE_4__["getCellBuilder"])(col.config || {}, style, _this.props),
            };
        });
    };
    Table.prototype.render = function () {
        var _a = this.props, showHeader = _a.showHeader, fixedHeader = _a.fixedHeader, fixedColumns = _a.fixedColumns, rotate = _a.rotate, width = _a.width, height = _a.height;
        var data = this.state.data;
        if (!data || !data.fields || !data.fields.length) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, "Missing Fields"); // nothing
        }
        var columnCount = data.fields.length;
        var rowCount = data.length + (showHeader ? 1 : 0);
        var fixedColumnCount = Math.min(fixedColumns, columnCount);
        var fixedRowCount = showHeader && fixedHeader ? 1 : 0;
        if (rotate) {
            var temp = columnCount;
            columnCount = rowCount;
            rowCount = temp;
            fixedRowCount = 0;
            fixedColumnCount = Math.min(fixedColumns, rowCount) + (showHeader && fixedHeader ? 1 : 0);
        }
        // Called after sort or the data changes
        var scroll = this.scrollToTop ? 1 : -1;
        var scrollToRow = rotate ? -1 : scroll;
        var scrollToColumn = rotate ? scroll : -1;
        if (this.scrollToTop) {
            this.scrollToTop = false;
        }
        // Force MultiGrid to rerender if these options change
        // See: https://github.com/bvaughn/react-virtualized#pass-thru-props
        var refreshKeys = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state, { d1: this.props.data, s0: this.props.styles });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_virtualized__WEBPACK_IMPORTED_MODULE_2__["MultiGrid"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, refreshKeys, { scrollToRow: scrollToRow, columnCount: columnCount, scrollToColumn: scrollToColumn, rowCount: rowCount, overscanColumnCount: 8, overscanRowCount: 8, columnWidth: this.getColumnWidth, deferredMeasurementCache: this.measurer, cellRenderer: this.cellRenderer, rowHeight: this.measurer.rowHeight, width: width, height: height, fixedColumnCount: fixedColumnCount, fixedRowCount: fixedRowCount, classNameTopLeftGrid: "gf-table-fixed-column", classNameBottomLeftGrid: "gf-table-fixed-column" })));
    };
    Table.defaultProps = {
        showHeader: true,
        fixedHeader: true,
        fixedColumns: 0,
        rotate: false,
        minColumnWidth: 150,
    };
    return Table;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

/* harmony default export */ __webpack_exports__["default"] = (Table);


/***/ }),

/***/ "./packages/grafana-ui/src/components/Table/TableCellBuilder.tsx":
/*!***********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Table/TableCellBuilder.tsx ***!
  \***********************************************************************/
/*! exports provided: simpleCellBuilder, getCellBuilder */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "simpleCellBuilder", function() { return simpleCellBuilder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCellBuilder", function() { return getCellBuilder; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _utils_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/index */ "./packages/grafana-ui/src/utils/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libraries




/** Simplest cell that just spits out the value */
var simpleCellBuilder = function (cell) {
    var props = cell.props, value = cell.value, className = cell.className;
    var style = props.style;
    return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { style: style, className: 'gf-table-cell ' + className }, value));
};
// private mapper:ValueMapper,
// private style:ColumnStyle,
// private theme:GrafanaTheme,
// private column:Column,
// private replaceVariables: InterpolateFunction,
// private fmt?:ValueFormatter) {
function getCellBuilder(schema, style, props) {
    if (!style) {
        return simpleCellBuilder;
    }
    if (style.type === 'hidden') {
        // TODO -- for hidden, we either need to:
        // 1. process the Table and remove hidden fields
        // 2. do special math to pick the right column skipping hidden fields
        throw new Error('hidden not supported!');
    }
    if (style.type === 'date') {
        return new CellBuilderWithStyle(function (v) {
            if (v === undefined || v === null) {
                return '-';
            }
            if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(v)) {
                v = v[0];
            }
            var date = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(v);
            if (false) {}
            return date.format(style.dateFormat);
        }, style, props.theme, schema, props.replaceVariables).build;
    }
    if (style.type === 'string') {
        return new CellBuilderWithStyle(function (v) {
            if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(v)) {
                v = v.join(', ');
            }
            return v;
        }, style, props.theme, schema, props.replaceVariables).build;
        // TODO!!!!  all the mapping stuff!!!!
    }
    if (style.type === 'number') {
        var valueFormatter = Object(_utils_index__WEBPACK_IMPORTED_MODULE_3__["getValueFormat"])(style.unit || schema.unit || 'none');
        return new CellBuilderWithStyle(function (v) {
            if (v === null || v === void 0) {
                return '-';
            }
            return v;
        }, style, props.theme, schema, props.replaceVariables, valueFormatter).build;
    }
    return simpleCellBuilder;
}
// Runs the value through a formatter and adds colors to the cell properties
var CellBuilderWithStyle = /** @class */ (function () {
    function CellBuilderWithStyle(mapper, style, theme, schema, replaceVariables, fmt) {
        var _this = this;
        this.mapper = mapper;
        this.style = style;
        this.theme = theme;
        this.schema = schema;
        this.replaceVariables = replaceVariables;
        this.fmt = fmt;
        this.getColorForValue = function (value) {
            var _a = _this.style, thresholds = _a.thresholds, colors = _a.colors;
            if (!thresholds || !colors) {
                return null;
            }
            for (var i = thresholds.length; i > 0; i--) {
                if (value >= thresholds[i - 1]) {
                    return Object(_utils_index__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(colors[i], _this.theme.type);
                }
            }
            return Object(_utils_index__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.first(colors), _this.theme.type);
        };
        this.build = function (cell) {
            var props = cell.props;
            var value = _this.mapper(cell.value);
            if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(value)) {
                if (_this.fmt) {
                    value = _this.fmt(value, _this.style.decimals);
                }
                // For numeric values set the color
                var colorMode = _this.style.colorMode;
                if (colorMode) {
                    var color = _this.getColorForValue(Number(value));
                    if (color) {
                        if (colorMode === 'cell') {
                            props = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props.style, { backgroundColor: color, color: 'white' }) });
                        }
                        else if (colorMode === 'value') {
                            props = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props.style, { color: color }) });
                        }
                    }
                }
            }
            var cellClasses = [];
            if (_this.style.preserveFormat) {
                cellClasses.push('table-panel-cell-pre');
            }
            if (_this.style.link) {
                // Render cell as link
                var row = cell.row;
                var scopedVars = {};
                if (row) {
                    for (var i = 0; i < row.length; i++) {
                        scopedVars["__cell_" + i] = { value: row[i] };
                    }
                }
                scopedVars['__cell'] = { value: value };
                var cellLink = _this.replaceVariables(_this.style.linkUrl, scopedVars, encodeURIComponent);
                var cellLinkTooltip = _this.replaceVariables(_this.style.linkTooltip, scopedVars);
                var cellTarget = _this.style.linkTargetBlank ? '_blank' : '';
                cellClasses.push('table-panel-cell-link');
                value = (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("a", { href: cellLink, target: cellTarget, "data-link-tooltip": true, "data-original-title": cellLinkTooltip, "data-placement": "right" }, value));
            }
            // ??? I don't think this will still work!
            if (_this.schema.filterable) {
                cellClasses.push('table-panel-cell-filterable');
                value = (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_2___default.a.Fragment, null,
                    value,
                    react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", null,
                        react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("a", { className: "table-panel-filter-link", "data-link-tooltip": true, "data-original-title": "Filter out value", "data-placement": "bottom", "data-row": props.rowIndex, "data-column": props.columnIndex, "data-operator": "!=" },
                            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("i", { className: "fa fa-search-minus" })),
                        react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("a", { className: "table-panel-filter-link", "data-link-tooltip": true, "data-original-title": "Filter for value", "data-placement": "bottom", "data-row": props.rowIndex, "data-column": props.columnIndex, "data-operator": "=" },
                            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("i", { className: "fa fa-search-plus" })))));
            }
            var className;
            if (cellClasses.length) {
                className = cellClasses.join(' ');
            }
            return simpleCellBuilder({ value: value, props: props, className: className });
        };
    }
    return CellBuilderWithStyle;
}());


/***/ }),

/***/ "./packages/grafana-ui/src/components/Table/TableInputCSV.tsx":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Table/TableInputCSV.tsx ***!
  \********************************************************************/
/*! exports provided: TableInputCSV, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TableInputCSV", function() { return TableInputCSV; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/debounce */ "./node_modules/lodash/debounce.js");
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_debounce__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




/**
 * Expects the container div to have size set and will fill it 100%
 */
var TableInputCSV = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TableInputCSV, _super);
    function TableInputCSV(props) {
        var _this = _super.call(this, props) || this;
        _this.readCSV = lodash_debounce__WEBPACK_IMPORTED_MODULE_2___default()(function () {
            var config = _this.props.config;
            var text = _this.state.text;
            _this.setState({ data: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["readCSV"])(text, { config: config }) });
        }, 150);
        _this.onTextChange = function (event) {
            _this.setState({ text: event.target.value });
        };
        var text = props.text, config = props.config;
        _this.state = {
            text: text,
            data: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["readCSV"])(text, { config: config }),
        };
        return _this;
    }
    TableInputCSV.prototype.componentDidUpdate = function (prevProps, prevState) {
        var text = this.state.text;
        if (text !== prevState.text || this.props.config !== prevProps.config) {
            this.readCSV();
        }
        // If the props text has changed, replace our local version
        if (this.props.text !== prevProps.text && this.props.text !== text) {
            this.setState({ text: this.props.text });
        }
        if (this.state.data !== prevState.data) {
            this.props.onSeriesParsed(this.state.data, this.state.text);
        }
    };
    TableInputCSV.prototype.render = function () {
        var _a = this.props, width = _a.width, height = _a.height;
        var data = this.state.data;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-table-input-csv" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("textarea", { style: { width: width, height: height }, placeholder: "Enter CSV here...", value: this.state.text, onChange: this.onTextChange, className: "gf-form-input" }),
            data && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("footer", null, data.map(function (frame, index) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: index },
                    "Rows:",
                    frame.length,
                    ", Columns:",
                    frame.fields.length,
                    " \u00A0",
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-check-circle" })));
            })))));
    };
    return TableInputCSV;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));

/* harmony default export */ __webpack_exports__["default"] = (TableInputCSV);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ThresholdsEditor/ThresholdsEditor.tsx":
/*!**********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ThresholdsEditor/ThresholdsEditor.tsx ***!
  \**********************************************************************************/
/*! exports provided: ThresholdsEditor, thresholdsWithoutKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThresholdsEditor", function() { return ThresholdsEditor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "thresholdsWithoutKey", function() { return thresholdsWithoutKey; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./packages/grafana-ui/src/utils/index.ts");
/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../themes */ "./packages/grafana-ui/src/themes/index.ts");
/* harmony import */ var _Input_Input__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Input/Input */ "./packages/grafana-ui/src/components/Input/Input.tsx");
/* harmony import */ var _ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../ColorPicker/ColorPicker */ "./packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx");
/* harmony import */ var _PanelOptionsGroup_PanelOptionsGroup__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../PanelOptionsGroup/PanelOptionsGroup */ "./packages/grafana-ui/src/components/PanelOptionsGroup/PanelOptionsGroup.tsx");









var counter = 100;
function toThresholdsWithKey(thresholds) {
    if (!thresholds || thresholds.length === 0) {
        thresholds = [{ value: -Infinity, color: 'green' }];
    }
    return thresholds.map(function (t) {
        return {
            color: t.color,
            value: t.value === null ? -Infinity : t.value,
            key: counter++,
        };
    });
}
var ThresholdsEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ThresholdsEditor, _super);
    function ThresholdsEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.onAddThresholdAfter = function (threshold) {
            var e_1, _a;
            var thresholds = _this.state.thresholds;
            var maxValue = 100;
            var minValue = 0;
            var prev = undefined;
            var next = undefined;
            try {
                for (var thresholds_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](thresholds), thresholds_1_1 = thresholds_1.next(); !thresholds_1_1.done; thresholds_1_1 = thresholds_1.next()) {
                    var t = thresholds_1_1.value;
                    if (prev && prev.key === threshold.key) {
                        next = t;
                        break;
                    }
                    prev = t;
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (thresholds_1_1 && !thresholds_1_1.done && (_a = thresholds_1.return)) _a.call(thresholds_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            var prevValue = prev && isFinite(prev.value) ? prev.value : minValue;
            var nextValue = next && isFinite(next.value) ? next.value : maxValue;
            var color = _utils__WEBPACK_IMPORTED_MODULE_3__["colors"].filter(function (c) { return !thresholds.some(function (t) { return t.color === c; }); })[1];
            var add = {
                value: prevValue + (nextValue - prevValue) / 2.0,
                color: color,
                key: counter++,
            };
            var newThresholds = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](thresholds, [add]);
            Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["sortThresholds"])(newThresholds);
            _this.setState({
                thresholds: newThresholds,
            }, function () { return _this.onChange(); });
        };
        _this.onRemoveThreshold = function (threshold) {
            var thresholds = _this.state.thresholds;
            if (!thresholds.length) {
                return;
            }
            // Don't remove index 0
            if (threshold.key === thresholds[0].key) {
                return;
            }
            _this.setState({
                thresholds: thresholds.filter(function (t) { return t.key !== threshold.key; }),
            }, function () { return _this.onChange(); });
        };
        _this.onChangeThresholdValue = function (event, threshold) {
            var cleanValue = event.target.value.replace(/,/g, '.');
            var parsedValue = parseFloat(cleanValue);
            var value = isNaN(parsedValue) ? '' : parsedValue;
            var thresholds = _this.state.thresholds.map(function (t) {
                if (t.key === threshold.key) {
                    t = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, t, { value: value });
                }
                return t;
            });
            if (thresholds.length) {
                thresholds[0].value = -Infinity;
            }
            _this.setState({ thresholds: thresholds });
        };
        _this.onChangeThresholdColor = function (threshold, color) {
            var thresholds = _this.state.thresholds;
            var newThresholds = thresholds.map(function (t) {
                if (t.key === threshold.key) {
                    t = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, t, { color: color });
                }
                return t;
            });
            _this.setState({
                thresholds: newThresholds,
            }, function () { return _this.onChange(); });
        };
        _this.onBlur = function () {
            var thresholds = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](_this.state.thresholds);
            Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["sortThresholds"])(thresholds);
            _this.setState({
                thresholds: thresholds,
            }, function () { return _this.onChange(); });
        };
        _this.onChange = function () {
            var thresholds = _this.state.thresholds;
            _this.props.onChange(thresholdsWithoutKey(thresholds));
        };
        _this.renderInput = function (threshold) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input-inner" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "thresholds-row-input-inner-arrow" }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input-inner-color" }, threshold.color && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input-inner-color-colorpicker" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_6__["ColorPicker"], { color: threshold.color, onChange: function (color) { return _this.onChangeThresholdColor(threshold, color); }, enableNamedColors: true })))),
                !isFinite(threshold.value) ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input-inner-value" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Input_Input__WEBPACK_IMPORTED_MODULE_5__["Input"], { type: "text", value: "Base", readOnly: true }))) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input-inner-value" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Input_Input__WEBPACK_IMPORTED_MODULE_5__["Input"], { type: "number", step: "0.0001", onChange: function (event) { return _this.onChangeThresholdValue(event, threshold); }, value: threshold.value, onBlur: _this.onBlur })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input-inner-remove", onClick: function () { return _this.onRemoveThreshold(threshold); } },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-times" }))))));
        };
        var thresholds = toThresholdsWithKey(props.thresholds);
        thresholds[0].value = -Infinity;
        _this.state = { thresholds: thresholds };
        return _this;
    }
    ThresholdsEditor.prototype.render = function () {
        var _this = this;
        var thresholds = this.state.thresholds;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_themes__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"].Consumer, null, function (theme) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PanelOptionsGroup_PanelOptionsGroup__WEBPACK_IMPORTED_MODULE_7__["PanelOptionsGroup"], { title: "Thresholds" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds" }, thresholds
                    .slice(0)
                    .reverse()
                    .map(function (threshold) {
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row", key: "" + threshold.key },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-add-button", onClick: function () { return _this.onAddThresholdAfter(threshold); } },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-plus" })),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-color-indicator", style: { backgroundColor: Object(_utils__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(threshold.color, theme.type) } }),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "thresholds-row-input" }, _this.renderInput(threshold))));
                }))));
        }));
    };
    return ThresholdsEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

function thresholdsWithoutKey(thresholds) {
    return thresholds.map(function (t) {
        var key = t.key, rest = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](t, ["key"]);
        return rest; // everything except key
    });
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/TimePicker/TimeOfDayPicker.tsx":
/*!***************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TimePicker/TimeOfDayPicker.tsx ***!
  \***************************************************************************/
/*! exports provided: TimeOfDayPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeOfDayPicker", function() { return TimeOfDayPicker; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var rc_time_picker__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rc-time-picker */ "./node_modules/rc-time-picker/es/index.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");



var TimeOfDayPicker = function (_a) {
    var _b = _a.minuteStep, minuteStep = _b === void 0 ? 1 : _b, _c = _a.showHour, showHour = _c === void 0 ? true : _c, onChange = _a.onChange, value = _a.value;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null,
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(rc_time_picker__WEBPACK_IMPORTED_MODULE_1__["default"], { defaultValue: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTimeAsMoment"])(), onChange: function (value) { return onChange(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(value)); }, allowEmpty: false, showSecond: false, value: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTimeAsMoment"])(value), showHour: showHour, minuteStep: minuteStep })));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/TimePicker/TimePicker.tsx":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TimePicker/TimePicker.tsx ***!
  \**********************************************************************/
/*! exports provided: defaultSelectOptions, TimePicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultSelectOptions", function() { return defaultSelectOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimePicker", function() { return TimePicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Select_ButtonSelect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Select/ButtonSelect */ "./packages/grafana-ui/src/components/Select/ButtonSelect.tsx");
/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");
/* harmony import */ var _TimePickerPopover__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./TimePickerPopover */ "./packages/grafana-ui/src/components/TimePicker/TimePickerPopover.tsx");
/* harmony import */ var _ClickOutsideWrapper_ClickOutsideWrapper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../ClickOutsideWrapper/ClickOutsideWrapper */ "./packages/grafana-ui/src/components/ClickOutsideWrapper/ClickOutsideWrapper.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _time__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./time */ "./packages/grafana-ui/src/components/TimePicker/time.ts");

// Libraries

// Components




// Utils & Services



// Types


var defaultSelectOptions = [
    { from: 'now-5m', to: 'now', display: 'Last 5 minutes', section: 3 },
    { from: 'now-15m', to: 'now', display: 'Last 15 minutes', section: 3 },
    { from: 'now-30m', to: 'now', display: 'Last 30 minutes', section: 3 },
    { from: 'now-1h', to: 'now', display: 'Last 1 hour', section: 3 },
    { from: 'now-3h', to: 'now', display: 'Last 3 hours', section: 3 },
    { from: 'now-6h', to: 'now', display: 'Last 6 hours', section: 3 },
    { from: 'now-12h', to: 'now', display: 'Last 12 hours', section: 3 },
    { from: 'now-24h', to: 'now', display: 'Last 24 hours', section: 3 },
    { from: 'now-2d', to: 'now', display: 'Last 2 days', section: 3 },
    { from: 'now-7d', to: 'now', display: 'Last 7 days', section: 3 },
    { from: 'now-30d', to: 'now', display: 'Last 30 days', section: 3 },
    { from: 'now-90d', to: 'now', display: 'Last 90 days', section: 3 },
    { from: 'now-6M', to: 'now', display: 'Last 6 months', section: 3 },
    { from: 'now-1y', to: 'now', display: 'Last 1 year', section: 3 },
    { from: 'now-2y', to: 'now', display: 'Last 2 years', section: 3 },
    { from: 'now-5y', to: 'now', display: 'Last 5 years', section: 3 },
    { from: 'now-1d/d', to: 'now-1d/d', display: 'Yesterday', section: 3 },
    { from: 'now-2d/d', to: 'now-2d/d', display: 'Day before yesterday', section: 3 },
    { from: 'now-7d/d', to: 'now-7d/d', display: 'This day last week', section: 3 },
    { from: 'now-1w/w', to: 'now-1w/w', display: 'Previous week', section: 3 },
    { from: 'now-1M/M', to: 'now-1M/M', display: 'Previous month', section: 3 },
    { from: 'now-1y/y', to: 'now-1y/y', display: 'Previous year', section: 3 },
    { from: 'now/d', to: 'now/d', display: 'Today', section: 3 },
    { from: 'now/d', to: 'now', display: 'Today so far', section: 3 },
    { from: 'now/w', to: 'now/w', display: 'This week', section: 3 },
    { from: 'now/w', to: 'now', display: 'This week so far', section: 3 },
    { from: 'now/M', to: 'now/M', display: 'This month', section: 3 },
    { from: 'now/M', to: 'now', display: 'This month so far', section: 3 },
    { from: 'now/y', to: 'now/y', display: 'This year', section: 3 },
    { from: 'now/y', to: 'now', display: 'This year so far', section: 3 },
];
var defaultZoomOutTooltip = function () {
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        "Time range zoom out ",
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
        " CTRL+Z"));
};
var TimePicker = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TimePicker, _super);
    function TimePicker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.pickerTriggerRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["createRef"])();
        _this.state = {
            isCustomOpen: false,
        };
        _this.mapTimeOptionsToSelectableValues = function (selectOptions) {
            var options = selectOptions.map(function (timeOption) {
                return {
                    label: timeOption.display,
                    value: timeOption,
                };
            });
            options.unshift({
                label: 'Custom time range',
                value: { from: 'custom', to: 'custom', display: 'Custom', section: 1 },
            });
            return options;
        };
        _this.onSelectChanged = function (item) {
            var _a = _this.props, onChange = _a.onChange, timeZone = _a.timeZone;
            if (item.value && item.value.from === 'custom') {
                // this is to prevent the ClickOutsideWrapper from directly closing the popover
                setTimeout(function () {
                    _this.setState({ isCustomOpen: true });
                }, 1);
                return;
            }
            if (item.value) {
                onChange(Object(_time__WEBPACK_IMPORTED_MODULE_7__["rawToTimeRange"])({ from: item.value.from, to: item.value.to }, timeZone));
            }
        };
        _this.onCustomChange = function (timeRange) {
            var onChange = _this.props.onChange;
            onChange(timeRange);
            _this.setState({ isCustomOpen: false });
        };
        _this.onCloseCustom = function () {
            _this.setState({ isCustomOpen: false });
        };
        return _this;
    }
    TimePicker.prototype.render = function () {
        var _a = this.props, selectTimeOptions = _a.selectOptions, value = _a.value, onMoveBackward = _a.onMoveBackward, onMoveForward = _a.onMoveForward, onZoom = _a.onZoom, timeZone = _a.timeZone;
        var isCustomOpen = this.state.isCustomOpen;
        var options = this.mapTimeOptionsToSelectableValues(selectTimeOptions);
        var currentOption = options.find(function (item) { return isTimeOptionEqualToTimeRange(item.value, value); });
        var isUTC = timeZone === 'utc';
        var adjustedTime = function (time) { return (isUTC ? time.utc() : time.local()) || null; };
        var adjustedTimeRange = {
            to: _grafana_data__WEBPACK_IMPORTED_MODULE_6__["dateMath"].isMathString(value.raw.to) ? value.raw.to : adjustedTime(value.to),
            from: _grafana_data__WEBPACK_IMPORTED_MODULE_6__["dateMath"].isMathString(value.raw.from) ? value.raw.from : adjustedTime(value.from),
        };
        var rangeString = _grafana_data__WEBPACK_IMPORTED_MODULE_6__["rangeUtil"].describeTimeRange(adjustedTimeRange);
        var label = (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            isCustomOpen && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, "Custom time range"),
            !isCustomOpen && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, rangeString),
            isUTC && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "time-picker-utc" }, "UTC")));
        var isAbsolute = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_6__["isDateTime"])(value.raw.to);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker", ref: this.pickerTriggerRef },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-buttons" },
                isAbsolute && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn navbar-button navbar-button--tight", onClick: onMoveBackward },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-chevron-left" }))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Select_ButtonSelect__WEBPACK_IMPORTED_MODULE_2__["ButtonSelect"], { className: "time-picker-button-select", value: currentOption, label: label, options: options, maxMenuHeight: 600, onChange: this.onSelectChanged, iconClass: 'fa fa-clock-o fa-fw', tooltipContent: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(TimePickerTooltipContent, { timeRange: value }) }),
                isAbsolute && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn navbar-button navbar-button--tight", onClick: onMoveForward },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-chevron-right" }))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_3__["Tooltip"], { content: defaultZoomOutTooltip, placement: "bottom" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn navbar-button navbar-button--zoom", onClick: onZoom },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-search-minus" }))),
                isCustomOpen && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ClickOutsideWrapper_ClickOutsideWrapper__WEBPACK_IMPORTED_MODULE_5__["ClickOutsideWrapper"], { onClick: this.onCloseCustom },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TimePickerPopover__WEBPACK_IMPORTED_MODULE_4__["TimePickerPopover"], { value: value, timeZone: timeZone, onChange: this.onCustomChange }))))));
    };
    return TimePicker;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var TimePickerTooltipContent = function (_a) {
    var timeRange = _a.timeRange;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        timeRange.from.format(_grafana_data__WEBPACK_IMPORTED_MODULE_6__["TIME_FORMAT"]),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "text-center" }, "to"),
        timeRange.to.format(_grafana_data__WEBPACK_IMPORTED_MODULE_6__["TIME_FORMAT"])));
};
function isTimeOptionEqualToTimeRange(option, range) {
    return range.raw.from === option.from && range.raw.to === option.to;
}


/***/ }),

/***/ "./packages/grafana-ui/src/components/TimePicker/TimePickerCalendar.tsx":
/*!******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TimePicker/TimePickerCalendar.tsx ***!
  \******************************************************************************/
/*! exports provided: TimePickerCalendar */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimePickerCalendar", function() { return TimePickerCalendar; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_calendar_dist_entry_nostyle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-calendar/dist/entry.nostyle */ "./node_modules/react-calendar/dist/entry.nostyle.js");
/* harmony import */ var react_calendar_dist_entry_nostyle__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_calendar_dist_entry_nostyle__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _time__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./time */ "./packages/grafana-ui/src/components/TimePicker/time.ts");






var TimePickerCalendar = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TimePickerCalendar, _super);
    function TimePickerCalendar() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onCalendarChange = function (date) {
            var _a = _this.props, onChange = _a.onChange, timeZone = _a.timeZone;
            if (Array.isArray(date)) {
                return;
            }
            var newDate = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(date);
            if (timeZone === 'utc') {
                newDate = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(newDate.format(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["TIME_FORMAT"]));
            }
            onChange(newDate);
        };
        _this.onDrilldown = function (props) {
            // this is to prevent clickout side wrapper from triggering when drilling down
            if (window.event) {
                // @ts-ignore
                window.event.stopPropagation();
            }
        };
        return _this;
    }
    TimePickerCalendar.prototype.render = function () {
        var _a = this.props, value = _a.value, roundup = _a.roundup, timeZone = _a.timeZone;
        var date = Object(_time__WEBPACK_IMPORTED_MODULE_4__["stringToDateTimeType"])(value, roundup, timeZone);
        if (!date.isValid()) {
            date = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])();
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_calendar_dist_entry_nostyle__WEBPACK_IMPORTED_MODULE_2___default.a, { value: date.toDate(), next2Label: null, prev2Label: null, className: "time-picker-calendar", tileClassName: "time-picker-calendar-tile", onChange: this.onCalendarChange, onDrillDown: this.onDrilldown, nextLabel: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "fa fa-angle-right" }), prevLabel: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "fa fa-angle-left" }) }));
    };
    return TimePickerCalendar;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/TimePicker/TimePickerInput.tsx":
/*!***************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TimePicker/TimePickerInput.tsx ***!
  \***************************************************************************/
/*! exports provided: TimePickerInput */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimePickerInput", function() { return TimePickerInput; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _Input_Input__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Input/Input */ "./packages/grafana-ui/src/components/Input/Input.tsx");
/* harmony import */ var _time__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./time */ "./packages/grafana-ui/src/components/TimePicker/time.ts");





var TimePickerInput = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TimePickerInput, _super);
    function TimePickerInput() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.isValid = function (value) {
            var _a = _this.props, timeZone = _a.timeZone, roundup = _a.roundup;
            if (value.indexOf('now') !== -1) {
                var isValid_1 = Object(_time__WEBPACK_IMPORTED_MODULE_4__["isValidTimeString"])(value);
                return isValid_1;
            }
            var parsed = Object(_time__WEBPACK_IMPORTED_MODULE_4__["stringToDateTimeType"])(value, roundup, timeZone);
            var isValid = parsed.isValid();
            return isValid;
        };
        _this.onChange = function (event) {
            var onChange = _this.props.onChange;
            var value = event.target.value;
            onChange(value, _this.isValid(value));
        };
        _this.valueToString = function (value) {
            if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["isDateTime"])(value)) {
                return value.format(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["TIME_FORMAT"]);
            }
            else {
                return value;
            }
        };
        return _this;
    }
    TimePickerInput.prototype.render = function () {
        var _a = this.props, value = _a.value, tabIndex = _a.tabIndex;
        var valueString = this.valueToString(value);
        var error = !this.isValid(valueString);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Input_Input__WEBPACK_IMPORTED_MODULE_3__["Input"], { type: "text", onChange: this.onChange, onBlur: this.onChange, hideErrorMessage: true, value: valueString, className: "time-picker-input" + (error ? '-error' : ''), tabIndex: tabIndex }));
    };
    return TimePickerInput;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/TimePicker/TimePickerPopover.tsx":
/*!*****************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TimePicker/TimePickerPopover.tsx ***!
  \*****************************************************************************/
/*! exports provided: TimePickerPopover */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimePickerPopover", function() { return TimePickerPopover; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _TimePickerCalendar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TimePickerCalendar */ "./packages/grafana-ui/src/components/TimePicker/TimePickerCalendar.tsx");
/* harmony import */ var _TimePickerInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./TimePickerInput */ "./packages/grafana-ui/src/components/TimePicker/TimePickerInput.tsx");
/* harmony import */ var _time__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./time */ "./packages/grafana-ui/src/components/TimePicker/time.ts");

// Libraries

// Components



var TimePickerPopover = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TimePickerPopover, _super);
    function TimePickerPopover(props) {
        var _this = _super.call(this, props) || this;
        _this.onFromInputChanged = function (value, valid) {
            _this.setState({ from: value, isFromInputValid: valid });
        };
        _this.onToInputChanged = function (value, valid) {
            _this.setState({ to: value, isToInputValid: valid });
        };
        _this.onFromCalendarChanged = function (value) {
            _this.setState({ from: value });
        };
        _this.onToCalendarChanged = function (value) {
            value.set('h', 23);
            value.set('m', 59);
            value.set('s', 59);
            _this.setState({ to: value });
        };
        _this.onApplyClick = function () {
            var _a = _this.props, onChange = _a.onChange, timeZone = _a.timeZone;
            var _b = _this.state, from = _b.from, to = _b.to;
            onChange(Object(_time__WEBPACK_IMPORTED_MODULE_4__["rawToTimeRange"])({ from: from, to: to }, timeZone));
        };
        _this.state = {
            from: props.value.raw.from,
            to: props.value.raw.to,
            isFromInputValid: true,
            isToInputValid: true,
        };
        return _this;
    }
    TimePickerPopover.prototype.render = function () {
        var timeZone = this.props.timeZone;
        var _a = this.state, isFromInputValid = _a.isFromInputValid, isToInputValid = _a.isToInputValid, from = _a.from, to = _a.to;
        var isValid = isFromInputValid && isToInputValid;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: TimePickerPopover.popoverClassName },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body-custom-ranges" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body-custom-ranges-input" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label" }, "From"),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TimePickerInput__WEBPACK_IMPORTED_MODULE_3__["TimePickerInput"], { roundup: false, timeZone: timeZone, value: from, onChange: this.onFromInputChanged, tabIndex: 1 }))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body-custom-ranges-calendar" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TimePickerCalendar__WEBPACK_IMPORTED_MODULE_2__["TimePickerCalendar"], { timeZone: timeZone, roundup: false, value: from, onChange: this.onFromCalendarChanged }))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body-custom-ranges" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body-custom-ranges-input" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label" }, "To"),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TimePickerInput__WEBPACK_IMPORTED_MODULE_3__["TimePickerInput"], { roundup: true, timeZone: timeZone, value: to, onChange: this.onToInputChanged, tabIndex: 2 }))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-body-custom-ranges-calendar" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TimePickerCalendar__WEBPACK_IMPORTED_MODULE_2__["TimePickerCalendar"], { roundup: true, timeZone: timeZone, value: to, onChange: this.onToCalendarChanged })))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "time-picker-popover-footer" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { type: "submit", className: "btn btn-success", disabled: !isValid, onClick: this.onApplyClick }, "Apply"))));
    };
    TimePickerPopover.popoverClassName = 'time-picker-popover';
    return TimePickerPopover;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/TimePicker/time.ts":
/*!***************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TimePicker/time.ts ***!
  \***************************************************************/
/*! exports provided: rawToTimeRange, stringToDateTimeType, mapTimeRangeToRangeString, isValidTimeString */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rawToTimeRange", function() { return rawToTimeRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringToDateTimeType", function() { return stringToDateTimeType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapTimeRangeToRangeString", function() { return mapTimeRangeToRangeString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidTimeString", function() { return isValidTimeString; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

var rawToTimeRange = function (raw, timeZone) {
    var from = stringToDateTimeType(raw.from, false, timeZone);
    var to = stringToDateTimeType(raw.to, true, timeZone);
    return { from: from, to: to, raw: raw };
};
var stringToDateTimeType = function (value, roundUp, timeZone) {
    if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["isDateTime"])(value)) {
        return value;
    }
    if (value.indexOf('now') !== -1) {
        if (!_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateMath"].isValid(value)) {
            return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])();
        }
        var parsed = _grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateMath"].parse(value, roundUp, timeZone);
        return parsed || Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])();
    }
    return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTimeForTimeZone"])(timeZone, value, _grafana_data__WEBPACK_IMPORTED_MODULE_0__["TIME_FORMAT"]);
};
var mapTimeRangeToRangeString = function (timeRange) {
    return _grafana_data__WEBPACK_IMPORTED_MODULE_0__["rangeUtil"].describeTimeRange(timeRange);
};
var isValidTimeString = function (text) { return _grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateMath"].isValid(text); };


/***/ }),

/***/ "./packages/grafana-ui/src/components/ToggleButtonGroup/ToggleButtonGroup.tsx":
/*!************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ToggleButtonGroup/ToggleButtonGroup.tsx ***!
  \************************************************************************************/
/*! exports provided: ToggleButtonGroup, ToggleButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleButtonGroup", function() { return ToggleButtonGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleButton", function() { return ToggleButton; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");



var ToggleButtonGroup = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ToggleButtonGroup, _super);
    function ToggleButtonGroup() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ToggleButtonGroup.prototype.render = function () {
        var _a = this.props, children = _a.children, label = _a.label, transparent = _a.transparent;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--align-center" },
            label && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label " + (transparent ? 'gf-form-label--transparent' : '') }, label),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "toggle-button-group " + (transparent ? 'toggle-button-group--transparent' : '') }, children)));
    };
    return ToggleButtonGroup;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var ToggleButton = function (_a) {
    var children = _a.children, selected = _a.selected, _b = _a.className, className = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? null : _c, tooltip = _a.tooltip, onChange = _a.onChange;
    var onClick = function (event) {
        event.stopPropagation();
        if (!selected && onChange) {
            onChange(value);
        }
    };
    var btnClassName = "btn " + className + (selected ? ' active' : '');
    var button = (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: btnClassName, onClick: onClick },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, children)));
    if (tooltip) {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_2__["Tooltip"], { content: tooltip, placement: "bottom" }, button));
    }
    else {
        return button;
    }
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/Tooltip/Popover.tsx":
/*!****************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Tooltip/Popover.tsx ***!
  \****************************************************************/
/*! exports provided: Popover */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Popover", function() { return Popover; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_popper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-popper */ "./node_modules/react-popper/lib/esm/index.js");
/* harmony import */ var _Portal_Portal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Portal/Portal */ "./packages/grafana-ui/src/components/Portal/Portal.tsx");
/* harmony import */ var react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-transition-group/Transition */ "./node_modules/react-transition-group/Transition.js");
/* harmony import */ var react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_4__);





var defaultTransitionStyles = {
    transition: 'opacity 200ms linear',
    opacity: 0,
};
var transitionStyles = {
    exited: { opacity: 0 },
    entering: { opacity: 0 },
    entered: { opacity: 1, transitionDelay: '0s' },
    exiting: { opacity: 0, transitionDelay: '500ms' },
};
var Popover = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Popover, _super);
    function Popover() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Popover.prototype.render = function () {
        var _a = this.props, content = _a.content, show = _a.show, placement = _a.placement, onMouseEnter = _a.onMouseEnter, onMouseLeave = _a.onMouseLeave, className = _a.className, wrapperClassName = _a.wrapperClassName, renderArrow = _a.renderArrow, referenceElement = _a.referenceElement, eventsEnabled = _a.eventsEnabled;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_popper__WEBPACK_IMPORTED_MODULE_2__["Manager"], null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_4___default.a, { in: show, timeout: 100, mountOnEnter: true, unmountOnExit: true }, function (transitionState) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Portal_Portal__WEBPACK_IMPORTED_MODULE_3__["Portal"], null,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_popper__WEBPACK_IMPORTED_MODULE_2__["Popper"], { placement: placement, referenceElement: referenceElement, eventsEnabled: eventsEnabled, 
                        // TODO: move modifiers config to popper controller
                        modifiers: { preventOverflow: { enabled: true, boundariesElement: 'window' } } }, function (_a) {
                        var ref = _a.ref, style = _a.style, placement = _a.placement, arrowProps = _a.arrowProps, scheduleUpdate = _a.scheduleUpdate;
                        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, ref: ref, style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, style, defaultTransitionStyles, transitionStyles[transitionState]), "data-placement": placement, className: "" + wrapperClassName },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: className },
                                typeof content === 'string' && content,
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.isValidElement(content) && react__WEBPACK_IMPORTED_MODULE_1___default.a.cloneElement(content),
                                typeof content === 'function' &&
                                    content({
                                        updatePopperPosition: scheduleUpdate,
                                    }),
                                renderArrow &&
                                    renderArrow({
                                        arrowProps: arrowProps,
                                        placement: placement,
                                    }))));
                    })));
            })));
    };
    Popover.defaultProps = {
        eventsEnabled: true,
    };
    return Popover;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Tooltip/PopoverController.tsx":
/*!**************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Tooltip/PopoverController.tsx ***!
  \**************************************************************************/
/*! exports provided: PopoverController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PopoverController", function() { return PopoverController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);


var PopoverController = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PopoverController, _super);
    function PopoverController(props) {
        var _this = _super.call(this, props) || this;
        _this.showPopper = function () {
            if (_this.hideTimeout) {
                clearTimeout(_this.hideTimeout);
            }
            _this.setState(function (prevState) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, prevState, { show: true })); });
        };
        _this.hidePopper = function () {
            if (_this.props.hideAfter !== 0) {
                _this.hideTimeout = setTimeout(function () {
                    _this.setState(function (prevState) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, prevState, { show: false })); });
                }, _this.props.hideAfter);
                return;
            }
            _this.setState(function (prevState) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, prevState, { show: false })); });
        };
        _this.state = {
            placement: _this.props.placement || 'auto',
            show: false,
        };
        return _this;
    }
    PopoverController.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        if (nextProps.placement && nextProps.placement !== this.state.placement) {
            this.setState(function (prevState) {
                return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, prevState, { placement: nextProps.placement || 'auto' });
            });
        }
    };
    PopoverController.prototype.render = function () {
        var _a = this.props, children = _a.children, content = _a.content;
        var _b = this.state, show = _b.show, placement = _b.placement;
        return children(this.showPopper, this.hidePopper, {
            show: show,
            placement: placement,
            content: content,
        });
    };
    return PopoverController;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx":
/*!****************************************************************!*\
  !*** ./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx ***!
  \****************************************************************/
/*! exports provided: Tooltip */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tooltip", function() { return Tooltip; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Popover__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Popover */ "./packages/grafana-ui/src/components/Tooltip/Popover.tsx");
/* harmony import */ var _PopoverController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./PopoverController */ "./packages/grafana-ui/src/components/Tooltip/PopoverController.tsx");




var Tooltip = function (_a) {
    var children = _a.children, theme = _a.theme, controllerProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["children", "theme"]);
    var tooltipTriggerRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["createRef"])();
    var popperBackgroundClassName = 'popper__background' + (theme ? ' popper__background--' + theme : '');
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PopoverController__WEBPACK_IMPORTED_MODULE_3__["PopoverController"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, controllerProps), function (showPopper, hidePopper, popperProps) {
        {
            /* Override internal 'show' state if passed in as prop */
        }
        var payloadProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, popperProps, { show: controllerProps.show !== undefined ? controllerProps.show : popperProps.show });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            tooltipTriggerRef.current && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Popover__WEBPACK_IMPORTED_MODULE_2__["Popover"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, payloadProps, { onMouseEnter: showPopper, onMouseLeave: hidePopper, referenceElement: tooltipTriggerRef.current, wrapperClassName: "popper", className: popperBackgroundClassName, renderArrow: function (_a) {
                    var arrowProps = _a.arrowProps, placement = _a.placement;
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ className: "popper__arrow", "data-placement": placement }, arrowProps)));
                } }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.cloneElement(children, {
                ref: tooltipTriggerRef,
                onMouseEnter: showPopper,
                onMouseLeave: hidePopper,
            })));
    }));
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/TransformersUI/FilterByNameTransformerEditor.tsx":
/*!*********************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TransformersUI/FilterByNameTransformerEditor.tsx ***!
  \*********************************************************************************************/
/*! exports provided: FilterByNameTransformerEditor, filterFieldsByNameTransformRegistryItem */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FilterByNameTransformerEditor", function() { return FilterByNameTransformerEditor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterFieldsByNameTransformRegistryItem", function() { return filterFieldsByNameTransformRegistryItem; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _List_InlineList__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../List/InlineList */ "./packages/grafana-ui/src/components/List/InlineList.tsx");






var FilterByNameTransformerEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FilterByNameTransformerEditor, _super);
    function FilterByNameTransformerEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.onFieldToggle = function (fieldName) {
            var selected = _this.state.selected;
            if (selected.indexOf(fieldName) > -1) {
                _this.onChange(selected.filter(function (s) { return s !== fieldName; }));
            }
            else {
                _this.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](selected, [fieldName]));
            }
        };
        _this.onChange = function (selected) {
            _this.setState({ selected: selected });
            _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { include: selected.join('|') }));
        };
        _this.state = {
            include: props.options.include || '',
            options: [],
            selected: [],
        };
        return _this;
    }
    FilterByNameTransformerEditor.prototype.componentDidMount = function () {
        this.initOptions();
    };
    FilterByNameTransformerEditor.prototype.initOptions = function () {
        var e_1, _a, e_2, _b, e_3, _c;
        var _d = this.props, input = _d.input, options = _d.options;
        var configuredOptions = options.include ? options.include.split('|') : [];
        var allNames = [];
        var byName = {};
        try {
            for (var input_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](input), input_1_1 = input_1.next(); !input_1_1.done; input_1_1 = input_1.next()) {
                var frame = input_1_1.value;
                try {
                    for (var _e = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](frame.fields)), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var field = _f.value;
                        var v = byName[field.name];
                        if (!v) {
                            v = byName[field.name] = {
                                name: field.name,
                                count: 0,
                            };
                            allNames.push(v);
                        }
                        v.count++;
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (input_1_1 && !input_1_1.done && (_a = input_1.return)) _a.call(input_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        if (configuredOptions.length) {
            var options_1 = [];
            var selected = [];
            try {
                for (var allNames_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](allNames), allNames_1_1 = allNames_1.next(); !allNames_1_1.done; allNames_1_1 = allNames_1.next()) {
                    var v = allNames_1_1.value;
                    if (configuredOptions.includes(v.name)) {
                        selected.push(v);
                    }
                    options_1.push(v);
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (allNames_1_1 && !allNames_1_1.done && (_c = allNames_1.return)) _c.call(allNames_1);
                }
                finally { if (e_3) throw e_3.error; }
            }
            this.setState({
                options: options_1,
                selected: selected.map(function (s) { return s.name; }),
            });
        }
        else {
            this.setState({ options: allNames, selected: [] });
        }
    };
    FilterByNameTransformerEditor.prototype.render = function () {
        var _this = this;
        var _a = this.state, options = _a.options, selected = _a.selected;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_List_InlineList__WEBPACK_IMPORTED_MODULE_5__["InlineList"], { items: options, renderItem: function (o, i) {
                    var label = "" + o.name + (o.count > 1 ? ' (' + o.count + ')' : '');
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                  margin-right: ", ";\n                "], ["\n                  margin-right: ", ";\n                "])), i === options.length - 1 ? '0' : '10px') },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(FilterPill, { onClick: function () {
                                _this.onFieldToggle(o.name);
                            }, label: label, selected: selected.indexOf(o.name) > -1 })));
                } })));
    };
    return FilterByNameTransformerEditor;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));

var FilterPill = function (_a) {
    var label = _a.label, selected = _a.selected, onClick = _a.onClick;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n        padding: ", " ", ";\n        color: white;\n        background: ", ";\n        border-radius: 16px;\n        display: inline-block;\n        cursor: pointer;\n      "], ["\n        padding: ", " ", ";\n        color: white;\n        background: ", ";\n        border-radius: 16px;\n        display: inline-block;\n        cursor: pointer;\n      "])), theme.spacing.xxs, theme.spacing.sm, selected ? theme.colors.blueLight : theme.colors.blueShade), onClick: onClick },
        selected && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["cx"])('fa fa-check', Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n              margin-right: 4px;\n            "], ["\n              margin-right: 4px;\n            "])))) })),
        label));
};
var filterFieldsByNameTransformRegistryItem = {
    id: _grafana_data__WEBPACK_IMPORTED_MODULE_2__["DataTransformerID"].filterFieldsByName,
    component: FilterByNameTransformerEditor,
    transformer: _grafana_data__WEBPACK_IMPORTED_MODULE_2__["transformersRegistry"].get(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["DataTransformerID"].filterFieldsByName),
    name: 'Filter by name',
    description: 'UI for filter by name transformation',
};
var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./packages/grafana-ui/src/components/TransformersUI/ReduceTransformerEditor.tsx":
/*!***************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TransformersUI/ReduceTransformerEditor.tsx ***!
  \***************************************************************************************/
/*! exports provided: ReduceTransformerEditor, reduceTransformRegistryItem */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReduceTransformerEditor", function() { return ReduceTransformerEditor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reduceTransformRegistryItem", function() { return reduceTransformRegistryItem; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _StatsPicker_StatsPicker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../StatsPicker/StatsPicker */ "./packages/grafana-ui/src/components/StatsPicker/StatsPicker.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




// TODO:  Minimal implementation, needs some <3
var ReduceTransformerEditor = function (_a) {
    var options = _a.options, onChange = _a.onChange, input = _a.input;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_StatsPicker_StatsPicker__WEBPACK_IMPORTED_MODULE_2__["StatsPicker"], { width: 25, placeholder: "Choose Stat", allowMultiple: true, stats: options.reducers || [], onChange: function (stats) {
            onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { reducers: stats }));
        } }));
};
var reduceTransformRegistryItem = {
    id: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["DataTransformerID"].reduce,
    component: ReduceTransformerEditor,
    transformer: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["transformersRegistry"].get(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["DataTransformerID"].reduce),
    name: 'Reduce',
    description: 'UI for reduce transformation',
};


/***/ }),

/***/ "./packages/grafana-ui/src/components/TransformersUI/TransformationRow.tsx":
/*!*********************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TransformersUI/TransformationRow.tsx ***!
  \*********************************************************************************/
/*! exports provided: TransformationRow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransformationRow", function() { return TransformationRow; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _themes_ThemeContext__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../themes/ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _JSONFormatter_JSONFormatter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../JSONFormatter/JSONFormatter */ "./packages/grafana-ui/src/components/JSONFormatter/JSONFormatter.tsx");





var getStyles = function (theme) { return ({
    title: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: flex;\n    padding: 4px 8px 4px 8px;\n    position: relative;\n    height: 35px;\n    background: ", ";\n    border-radius: 4px 4px 0 0;\n    flex-wrap: nowrap;\n    justify-content: space-between;\n    align-items: center;\n  "], ["\n    display: flex;\n    padding: 4px 8px 4px 8px;\n    position: relative;\n    height: 35px;\n    background: ", ";\n    border-radius: 4px 4px 0 0;\n    flex-wrap: nowrap;\n    justify-content: space-between;\n    align-items: center;\n  "])), theme.colors.textFaint),
    name: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    font-weight: ", ";\n    color: ", ";\n  "], ["\n    font-weight: ", ";\n    color: ", ";\n  "])), theme.typography.weight.semibold, theme.colors.blue),
    iconRow: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    display: flex;\n  "], ["\n    display: flex;\n  "]))),
    icon: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    background: transparent;\n    border: none;\n    box-shadow: none;\n    cursor: pointer;\n    color: ", ";\n    margin-left: ", ";\n    &:hover {\n      color: ", ";\n    }\n  "], ["\n    background: transparent;\n    border: none;\n    box-shadow: none;\n    cursor: pointer;\n    color: ", ";\n    margin-left: ", ";\n    &:hover {\n      color: ", ";\n    }\n  "])), theme.colors.textWeak, theme.spacing.sm, theme.colors.text),
    editor: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_5 || (templateObject_5 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    border: 2px dashed ", ";\n    border-top: none;\n    border-radius: 0 0 4px 4px;\n    padding: 8px;\n  "], ["\n    border: 2px dashed ", ";\n    border-top: none;\n    border-radius: 0 0 4px 4px;\n    padding: 8px;\n  "])), theme.colors.textFaint),
}); };
var TransformationRow = function (_a) {
    var onRemove = _a.onRemove, editor = _a.editor, name = _a.name, input = _a.input;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_themes_ThemeContext__WEBPACK_IMPORTED_MODULE_2__["ThemeContext"]);
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(false), 2), viewDebug = _b[0], setViewDebug = _b[1];
    var styles = getStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_6 || (templateObject_6 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n        margin-bottom: 10px;\n      "], ["\n        margin-bottom: 10px;\n      "]))) },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.title },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.name }, name),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.iconRow },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { onClick: function () { return setViewDebug(!viewDebug); }, className: styles.icon },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-bug" })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { onClick: onRemove, className: styles.icon },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-trash" })))),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.editor },
            editor,
            viewDebug && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_JSONFormatter_JSONFormatter__WEBPACK_IMPORTED_MODULE_4__["JSONFormatter"], { json: input }))))));
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5, templateObject_6;


/***/ }),

/***/ "./packages/grafana-ui/src/components/TransformersUI/TransformationsEditor.tsx":
/*!*************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TransformersUI/TransformationsEditor.tsx ***!
  \*************************************************************************************/
/*! exports provided: TransformationsEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransformationsEditor", function() { return TransformationsEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _Select_Select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Select/Select */ "./packages/grafana-ui/src/components/Select/Select.tsx");
/* harmony import */ var _transformers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./transformers */ "./packages/grafana-ui/src/components/TransformersUI/transformers.ts");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _TransformationRow__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./TransformationRow */ "./packages/grafana-ui/src/components/TransformersUI/TransformationRow.tsx");
/* harmony import */ var _Button_Button__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Button/Button */ "./packages/grafana-ui/src/components/Button/Button.tsx");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");








var TransformationsEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TransformationsEditor, _super);
    function TransformationsEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { updateCounter: 0 };
        _this.onTransformationAdd = function () {
            var _a = _this.props, transformations = _a.transformations, onChange = _a.onChange;
            onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](transformations, [
                {
                    id: _grafana_data__WEBPACK_IMPORTED_MODULE_1__["DataTransformerID"].noop,
                    options: {},
                },
            ]));
            _this.setState({ updateCounter: _this.state.updateCounter + 1 });
        };
        _this.onTransformationChange = function (idx, config) {
            var _a = _this.props, transformations = _a.transformations, onChange = _a.onChange;
            transformations[idx] = config;
            onChange(transformations);
            _this.setState({ updateCounter: _this.state.updateCounter + 1 });
        };
        _this.onTransformationRemove = function (idx) {
            var _a = _this.props, transformations = _a.transformations, onChange = _a.onChange;
            transformations.splice(idx, 1);
            onChange(transformations);
            _this.setState({ updateCounter: _this.state.updateCounter + 1 });
        };
        _this.renderTransformationEditors = function () {
            var _a = _this.props, transformations = _a.transformations, dataFrames = _a.dataFrames;
            var hasTransformations = transformations.length > 0;
            var preTransformData = dataFrames;
            if (!hasTransformations) {
                return undefined;
            }
            var availableTransformers = _transformers__WEBPACK_IMPORTED_MODULE_3__["transformersUIRegistry"].list().map(function (t) {
                return {
                    value: t.transformer.id,
                    label: t.transformer.name,
                };
            });
            return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_4___default.a.Fragment, null, transformations.map(function (t, i) {
                var editor, input;
                if (t.id === _grafana_data__WEBPACK_IMPORTED_MODULE_1__["DataTransformerID"].noop) {
                    return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_Select_Select__WEBPACK_IMPORTED_MODULE_2__["Select"], { className: Object(emotion__WEBPACK_IMPORTED_MODULE_7__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                  margin-bottom: 10px;\n                "], ["\n                  margin-bottom: 10px;\n                "]))), key: t.id + "-" + i, options: availableTransformers, placeholder: "Select transformation", onChange: function (v) {
                            _this.onTransformationChange(i, {
                                id: v.value,
                                options: {},
                            });
                        } }));
                }
                var transformationUI = _transformers__WEBPACK_IMPORTED_MODULE_3__["transformersUIRegistry"].getIfExists(t.id);
                input = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["transformDataFrame"])(transformations.slice(0, i), preTransformData);
                if (transformationUI) {
                    editor = react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(transformationUI.component, {
                        options: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, transformationUI.transformer.defaultOptions, t.options),
                        input: input,
                        onChange: function (options) {
                            _this.onTransformationChange(i, {
                                id: t.id,
                                options: options,
                            });
                        },
                    });
                }
                return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_TransformationRow__WEBPACK_IMPORTED_MODULE_5__["TransformationRow"], { key: t.id + "-" + i, input: input || [], onRemove: function () { return _this.onTransformationRemove(i); }, editor: editor, name: transformationUI ? transformationUI.name : '', description: transformationUI ? transformationUI.description : '' }));
            })));
        };
        return _this;
    }
    TransformationsEditor.prototype.render = function () {
        return (react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_4___default.a.Fragment, null,
            this.renderTransformationEditors(),
            react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_Button_Button__WEBPACK_IMPORTED_MODULE_6__["Button"], { variant: "inverse", icon: "fa fa-plus", onClick: this.onTransformationAdd }, "Add transformation")));
    };
    return TransformationsEditor;
}(react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent));

var templateObject_1;


/***/ }),

/***/ "./packages/grafana-ui/src/components/TransformersUI/transformers.ts":
/*!***************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/TransformersUI/transformers.ts ***!
  \***************************************************************************/
/*! exports provided: transformersUIRegistry */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformersUIRegistry", function() { return transformersUIRegistry; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _ReduceTransformerEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ReduceTransformerEditor */ "./packages/grafana-ui/src/components/TransformersUI/ReduceTransformerEditor.tsx");
/* harmony import */ var _FilterByNameTransformerEditor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./FilterByNameTransformerEditor */ "./packages/grafana-ui/src/components/TransformersUI/FilterByNameTransformerEditor.tsx");



var transformersUIRegistry = new _grafana_data__WEBPACK_IMPORTED_MODULE_0__["Registry"](function () {
    return [_ReduceTransformerEditor__WEBPACK_IMPORTED_MODULE_1__["reduceTransformRegistryItem"], _FilterByNameTransformerEditor__WEBPACK_IMPORTED_MODULE_2__["filterFieldsByNameTransformRegistryItem"]];
});


/***/ }),

/***/ "./packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx":
/*!**********************************************************************!*\
  !*** ./packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx ***!
  \**********************************************************************/
/*! exports provided: UnitPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnitPicker", function() { return UnitPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! .. */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./packages/grafana-ui/src/utils/index.ts");




var UnitPicker = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UnitPicker, _super);
    function UnitPicker() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    UnitPicker.prototype.render = function () {
        var _a = this.props, defaultValue = _a.defaultValue, onChange = _a.onChange, width = _a.width;
        var unitGroups = Object(_utils__WEBPACK_IMPORTED_MODULE_3__["getValueFormats"])();
        // Need to transform the data structure to work well with Select
        var groupOptions = unitGroups.map(function (group) {
            var options = group.submenu.map(function (unit) {
                return {
                    label: unit.text,
                    value: unit.value,
                };
            });
            return {
                label: group.text,
                options: options,
            };
        });
        var value = groupOptions.map(function (group) {
            return group.options.find(function (option) { return option.value === defaultValue; });
        });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["Select"], { width: width, defaultValue: value, isSearchable: true, options: groupOptions, placeholder: "Choose", onChange: onChange }));
    };
    UnitPicker.defaultProps = {
        width: 12,
    };
    return UnitPicker;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/ValueMappingsEditor/MappingRow.tsx":
/*!*******************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ValueMappingsEditor/MappingRow.tsx ***!
  \*******************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! .. */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




var mappingOptions = [
    { value: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["MappingType"].ValueToText, label: 'Value' },
    { value: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["MappingType"].RangeToText, label: 'Range' },
];
var MappingRow = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MappingRow, _super);
    function MappingRow(props) {
        var _this = _super.call(this, props) || this;
        _this.onMappingValueChange = function (event) {
            _this.setState({ value: event.target.value });
        };
        _this.onMappingFromChange = function (event) {
            _this.setState({ from: event.target.value });
        };
        _this.onMappingToChange = function (event) {
            _this.setState({ to: event.target.value });
        };
        _this.onMappingTextChange = function (event) {
            _this.setState({ text: event.target.value });
        };
        _this.onMappingTypeChange = function (mappingType) {
            _this.setState({ type: mappingType });
        };
        _this.updateMapping = function () {
            _this.props.updateValueMapping(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.state));
        };
        _this.state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props.valueMapping);
        return _this;
    }
    MappingRow.prototype.renderRow = function () {
        var _a = this.state, from = _a.from, text = _a.text, to = _a.to, type = _a.type, value = _a.value;
        if (type === _grafana_data__WEBPACK_IMPORTED_MODULE_3__["MappingType"].RangeToText) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "From", labelWidth: 4, inputWidth: 8, onBlur: this.updateMapping, onChange: this.onMappingFromChange, value: from }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "To", labelWidth: 4, inputWidth: 8, onBlur: this.updateMapping, onChange: this.onMappingToChange, value: to }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: 4 }, "Text"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input", onBlur: this.updateMapping, value: text, onChange: this.onMappingTextChange }))));
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Value", labelWidth: 4, onBlur: this.updateMapping, onChange: this.onMappingValueChange, value: value, inputWidth: 8 }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: 4 }, "Text"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input", onBlur: this.updateMapping, value: text, onChange: this.onMappingTextChange }))));
    };
    MappingRow.prototype.render = function () {
        var _this = this;
        var type = this.state.type;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: 5 }, "Type"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(___WEBPACK_IMPORTED_MODULE_2__["Select"], { placeholder: "Choose type", isSearchable: false, options: mappingOptions, value: mappingOptions.find(function (o) { return o.value === type; }), 
                    // @ts-ignore
                    onChange: function (type) { return _this.onMappingTypeChange(type.value); }, width: 7 })),
            this.renderRow(),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { onClick: this.props.removeValueMapping, className: "gf-form-label gf-form-label--btn" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-times" })))));
    };
    return MappingRow;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
/* harmony default export */ __webpack_exports__["default"] = (MappingRow);


/***/ }),

/***/ "./packages/grafana-ui/src/components/ValueMappingsEditor/ValueMappingsEditor.tsx":
/*!****************************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/ValueMappingsEditor/ValueMappingsEditor.tsx ***!
  \****************************************************************************************/
/*! exports provided: ValueMappingsEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueMappingsEditor", function() { return ValueMappingsEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _MappingRow__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./MappingRow */ "./packages/grafana-ui/src/components/ValueMappingsEditor/MappingRow.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../index */ "./packages/grafana-ui/src/components/index.ts");
/* harmony import */ var _PanelOptionsGroup_PanelOptionsGroup__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../PanelOptionsGroup/PanelOptionsGroup */ "./packages/grafana-ui/src/components/PanelOptionsGroup/PanelOptionsGroup.tsx");






var ValueMappingsEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ValueMappingsEditor, _super);
    function ValueMappingsEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.onAddMapping = function () {
            return _this.setState(function (prevState) { return ({
                valueMappings: tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](prevState.valueMappings, [
                    {
                        id: prevState.nextIdToAdd,
                        operator: '',
                        value: '',
                        text: '',
                        type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["MappingType"].ValueToText,
                        from: '',
                        to: '',
                    },
                ]),
                nextIdToAdd: prevState.nextIdToAdd + 1,
            }); });
        };
        _this.onRemoveMapping = function (id) {
            _this.setState(function (prevState) { return ({
                valueMappings: prevState.valueMappings.filter(function (m) {
                    return m.id !== id;
                }),
            }); }, function () {
                _this.props.onChange(_this.state.valueMappings);
            });
        };
        _this.updateGauge = function (mapping) {
            _this.setState(function (prevState) { return ({
                valueMappings: prevState.valueMappings.map(function (m) {
                    if (m.id === mapping.id) {
                        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, mapping);
                    }
                    return m;
                }),
            }); }, function () {
                _this.props.onChange(_this.state.valueMappings);
            });
        };
        var mappings = props.valueMappings || [];
        _this.state = {
            valueMappings: mappings,
            nextIdToAdd: mappings.length > 0 ? _this.getMaxIdFromValueMappings(mappings) : 1,
        };
        return _this;
    }
    ValueMappingsEditor.prototype.getMaxIdFromValueMappings = function (mappings) {
        return Math.max.apply(null, mappings.map(function (mapping) { return mapping.id; }).map(function (m) { return m; })) + 1;
    };
    ValueMappingsEditor.prototype.render = function () {
        var _this = this;
        var valueMappings = this.state.valueMappings;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PanelOptionsGroup_PanelOptionsGroup__WEBPACK_IMPORTED_MODULE_5__["PanelOptionsGroup"], { title: "Value mappings" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
                valueMappings.length > 0 &&
                    valueMappings.map(function (valueMapping, index) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_MappingRow__WEBPACK_IMPORTED_MODULE_2__["default"], { key: valueMapping.text + "-" + index, valueMapping: valueMapping, updateValueMapping: _this.updateGauge, removeValueMapping: function () { return _this.onRemoveMapping(valueMapping.id); } })); }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_index__WEBPACK_IMPORTED_MODULE_4__["Button"], { variant: "inverse", icon: "fa fa-plus", onClick: this.onAddMapping }, "Add mapping"))));
    };
    return ValueMappingsEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx ***!
  \************************************************************************/
/*! exports provided: VizRepeater */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VizRepeater", function() { return VizRepeater; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../types */ "./packages/grafana-ui/src/types/index.ts");



var VizRepeater = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VizRepeater, _super);
    function VizRepeater(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            values: props.getValues(),
        };
        return _this;
    }
    VizRepeater.prototype.componentDidUpdate = function (prevProps) {
        var _a = this.props, renderCounter = _a.renderCounter, source = _a.source;
        if (renderCounter !== prevProps.renderCounter || source !== prevProps.source) {
            this.setState({ values: this.props.getValues() });
        }
    };
    VizRepeater.prototype.getOrientation = function () {
        var _a = this.props, orientation = _a.orientation, width = _a.width, height = _a.height;
        if (orientation === _types__WEBPACK_IMPORTED_MODULE_2__["VizOrientation"].Auto) {
            if (width > height) {
                return _types__WEBPACK_IMPORTED_MODULE_2__["VizOrientation"].Vertical;
            }
            else {
                return _types__WEBPACK_IMPORTED_MODULE_2__["VizOrientation"].Horizontal;
            }
        }
        return orientation;
    };
    VizRepeater.prototype.render = function () {
        var _a = this.props, renderValue = _a.renderValue, height = _a.height, width = _a.width, itemSpacing = _a.itemSpacing;
        var values = this.state.values;
        var orientation = this.getOrientation();
        var itemStyles = {
            display: 'flex',
        };
        var repeaterStyle = {
            display: 'flex',
        };
        var vizHeight = height;
        var vizWidth = width;
        if (orientation === _types__WEBPACK_IMPORTED_MODULE_2__["VizOrientation"].Horizontal) {
            repeaterStyle.flexDirection = 'column';
            itemStyles.marginBottom = itemSpacing + "px";
            vizWidth = width;
            vizHeight = height / values.length - itemSpacing;
        }
        else {
            repeaterStyle.flexDirection = 'row';
            itemStyles.marginRight = itemSpacing + "px";
            vizHeight = height;
            vizWidth = width / values.length - itemSpacing;
        }
        itemStyles.width = vizWidth + "px";
        itemStyles.height = vizHeight + "px";
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: repeaterStyle }, values.map(function (value, index) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { key: index, style: itemStyles }, renderValue(value, vizWidth, vizHeight)));
        })));
    };
    VizRepeater.defaultProps = {
        itemSpacing: 10,
    };
    return VizRepeater;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./packages/grafana-ui/src/components/index.ts":
/*!*****************************************************!*\
  !*** ./packages/grafana-ui/src/components/index.ts ***!
  \*****************************************************/
/*! exports provided: DeleteButton, Tooltip, PopoverContent, PopoverController, Popover, Portal, CustomScrollbar, Button, LinkButton, ButtonVariant, Select, AsyncSelect, IndicatorsContainer, NoOptionsMessage, resetSelectStyles, ButtonSelect, FormLabel, FormField, SecretFormField, LoadingPlaceholder, ColorPicker, SeriesColorPicker, SeriesColorPickerPopover, SeriesColorPickerPopoverWithTheme, PanelOptionsGroup, PanelOptionsGrid, ValueMappingsEditor, Switch, EmptySearchResult, PieChart, PieChartType, UnitPicker, StatsPicker, Input, InputStatus, RefreshPicker, TimePicker, TimeOfDayPicker, List, SetInterval, Table, TableInputCSV, BigValue, Gauge, Graph, GraphLegend, GraphWithLegend, BarGauge, VizRepeater, LegendOptions, LegendBasicOptions, LegendRenderOptions, LegendList, LegendTable, LegendItem, LegendPlacement, LegendDisplayMode, Alert, GraphSeriesToggler, GraphSeriesTogglerAPI, Collapse, LogLabels, LogRows, getLogRowStyles, ToggleButtonGroup, ToggleButton, ThresholdsEditor, ClickOutsideWrapper, FieldDisplayEditor, FieldPropertiesEditor, SingleStatBaseOptions, sharedSingleStatPanelChangedHandler, sharedSingleStatMigrationHandler, convertOldAngulrValueMapping, CallToActionCard, ContextMenu, ContextMenuItem, ContextMenuGroup, ContextMenuProps, VariableSuggestion, VariableOrigin, DataLinksEditor, DataLinksContextMenu, SeriesIcon, transformersUIRegistry, TransformationRow, TransformationsEditor, JSONFormatter, JsonExplorer, ErrorBoundary, ErrorBoundaryAlert, AlphaNotice */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _DeleteButton_DeleteButton__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DeleteButton/DeleteButton */ "./packages/grafana-ui/src/components/DeleteButton/DeleteButton.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeleteButton", function() { return _DeleteButton_DeleteButton__WEBPACK_IMPORTED_MODULE_0__["DeleteButton"]; });

/* harmony import */ var _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Tooltip/Tooltip */ "./packages/grafana-ui/src/components/Tooltip/Tooltip.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tooltip", function() { return _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_1__["Tooltip"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PopoverContent", function() { return _Tooltip_Tooltip__WEBPACK_IMPORTED_MODULE_1__["PopoverContent"]; });

/* harmony import */ var _Tooltip_PopoverController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Tooltip/PopoverController */ "./packages/grafana-ui/src/components/Tooltip/PopoverController.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PopoverController", function() { return _Tooltip_PopoverController__WEBPACK_IMPORTED_MODULE_2__["PopoverController"]; });

/* harmony import */ var _Tooltip_Popover__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Tooltip/Popover */ "./packages/grafana-ui/src/components/Tooltip/Popover.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Popover", function() { return _Tooltip_Popover__WEBPACK_IMPORTED_MODULE_3__["Popover"]; });

/* harmony import */ var _Portal_Portal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Portal/Portal */ "./packages/grafana-ui/src/components/Portal/Portal.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Portal", function() { return _Portal_Portal__WEBPACK_IMPORTED_MODULE_4__["Portal"]; });

/* harmony import */ var _CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CustomScrollbar/CustomScrollbar */ "./packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomScrollbar", function() { return _CustomScrollbar_CustomScrollbar__WEBPACK_IMPORTED_MODULE_5__["CustomScrollbar"]; });

/* harmony import */ var _Button_Button__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Button/Button */ "./packages/grafana-ui/src/components/Button/Button.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return _Button_Button__WEBPACK_IMPORTED_MODULE_6__["Button"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinkButton", function() { return _Button_Button__WEBPACK_IMPORTED_MODULE_6__["LinkButton"]; });

/* harmony import */ var _Button_AbstractButton__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Button/AbstractButton */ "./packages/grafana-ui/src/components/Button/AbstractButton.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ButtonVariant", function() { return _Button_AbstractButton__WEBPACK_IMPORTED_MODULE_7__["ButtonVariant"]; });

/* harmony import */ var _Select_Select__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Select/Select */ "./packages/grafana-ui/src/components/Select/Select.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Select", function() { return _Select_Select__WEBPACK_IMPORTED_MODULE_8__["Select"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncSelect", function() { return _Select_Select__WEBPACK_IMPORTED_MODULE_8__["AsyncSelect"]; });

/* harmony import */ var _Select_IndicatorsContainer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Select/IndicatorsContainer */ "./packages/grafana-ui/src/components/Select/IndicatorsContainer.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IndicatorsContainer", function() { return _Select_IndicatorsContainer__WEBPACK_IMPORTED_MODULE_9__["IndicatorsContainer"]; });

/* harmony import */ var _Select_NoOptionsMessage__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Select/NoOptionsMessage */ "./packages/grafana-ui/src/components/Select/NoOptionsMessage.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoOptionsMessage", function() { return _Select_NoOptionsMessage__WEBPACK_IMPORTED_MODULE_10__["NoOptionsMessage"]; });

/* harmony import */ var _Select_resetSelectStyles__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Select/resetSelectStyles */ "./packages/grafana-ui/src/components/Select/resetSelectStyles.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "resetSelectStyles", function() { return _Select_resetSelectStyles__WEBPACK_IMPORTED_MODULE_11__["default"]; });

/* harmony import */ var _Select_ButtonSelect__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Select/ButtonSelect */ "./packages/grafana-ui/src/components/Select/ButtonSelect.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ButtonSelect", function() { return _Select_ButtonSelect__WEBPACK_IMPORTED_MODULE_12__["ButtonSelect"]; });

/* harmony import */ var _FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./FormLabel/FormLabel */ "./packages/grafana-ui/src/components/FormLabel/FormLabel.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormLabel", function() { return _FormLabel_FormLabel__WEBPACK_IMPORTED_MODULE_13__["FormLabel"]; });

/* harmony import */ var _FormField_FormField__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./FormField/FormField */ "./packages/grafana-ui/src/components/FormField/FormField.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormField", function() { return _FormField_FormField__WEBPACK_IMPORTED_MODULE_14__["FormField"]; });

/* harmony import */ var _SecretFormFied_SecretFormField__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SecretFormFied/SecretFormField */ "./packages/grafana-ui/src/components/SecretFormFied/SecretFormField.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SecretFormField", function() { return _SecretFormFied_SecretFormField__WEBPACK_IMPORTED_MODULE_15__["SecretFormField"]; });

/* harmony import */ var _LoadingPlaceholder_LoadingPlaceholder__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./LoadingPlaceholder/LoadingPlaceholder */ "./packages/grafana-ui/src/components/LoadingPlaceholder/LoadingPlaceholder.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoadingPlaceholder", function() { return _LoadingPlaceholder_LoadingPlaceholder__WEBPACK_IMPORTED_MODULE_16__["LoadingPlaceholder"]; });

/* harmony import */ var _ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./ColorPicker/ColorPicker */ "./packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return _ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_17__["ColorPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPicker", function() { return _ColorPicker_ColorPicker__WEBPACK_IMPORTED_MODULE_17__["SeriesColorPicker"]; });

/* harmony import */ var _ColorPicker_SeriesColorPickerPopover__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./ColorPicker/SeriesColorPickerPopover */ "./packages/grafana-ui/src/components/ColorPicker/SeriesColorPickerPopover.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPickerPopover", function() { return _ColorPicker_SeriesColorPickerPopover__WEBPACK_IMPORTED_MODULE_18__["SeriesColorPickerPopover"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPickerPopoverWithTheme", function() { return _ColorPicker_SeriesColorPickerPopover__WEBPACK_IMPORTED_MODULE_18__["SeriesColorPickerPopoverWithTheme"]; });

/* harmony import */ var _PanelOptionsGroup_PanelOptionsGroup__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./PanelOptionsGroup/PanelOptionsGroup */ "./packages/grafana-ui/src/components/PanelOptionsGroup/PanelOptionsGroup.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelOptionsGroup", function() { return _PanelOptionsGroup_PanelOptionsGroup__WEBPACK_IMPORTED_MODULE_19__["PanelOptionsGroup"]; });

/* harmony import */ var _PanelOptionsGrid_PanelOptionsGrid__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./PanelOptionsGrid/PanelOptionsGrid */ "./packages/grafana-ui/src/components/PanelOptionsGrid/PanelOptionsGrid.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelOptionsGrid", function() { return _PanelOptionsGrid_PanelOptionsGrid__WEBPACK_IMPORTED_MODULE_20__["PanelOptionsGrid"]; });

/* harmony import */ var _ValueMappingsEditor_ValueMappingsEditor__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./ValueMappingsEditor/ValueMappingsEditor */ "./packages/grafana-ui/src/components/ValueMappingsEditor/ValueMappingsEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueMappingsEditor", function() { return _ValueMappingsEditor_ValueMappingsEditor__WEBPACK_IMPORTED_MODULE_21__["ValueMappingsEditor"]; });

/* harmony import */ var _Switch_Switch__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Switch/Switch */ "./packages/grafana-ui/src/components/Switch/Switch.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Switch", function() { return _Switch_Switch__WEBPACK_IMPORTED_MODULE_22__["Switch"]; });

/* harmony import */ var _EmptySearchResult_EmptySearchResult__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./EmptySearchResult/EmptySearchResult */ "./packages/grafana-ui/src/components/EmptySearchResult/EmptySearchResult.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmptySearchResult", function() { return _EmptySearchResult_EmptySearchResult__WEBPACK_IMPORTED_MODULE_23__["EmptySearchResult"]; });

/* harmony import */ var _PieChart_PieChart__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./PieChart/PieChart */ "./packages/grafana-ui/src/components/PieChart/PieChart.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PieChart", function() { return _PieChart_PieChart__WEBPACK_IMPORTED_MODULE_24__["PieChart"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PieChartType", function() { return _PieChart_PieChart__WEBPACK_IMPORTED_MODULE_24__["PieChartType"]; });

/* harmony import */ var _UnitPicker_UnitPicker__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./UnitPicker/UnitPicker */ "./packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnitPicker", function() { return _UnitPicker_UnitPicker__WEBPACK_IMPORTED_MODULE_25__["UnitPicker"]; });

/* harmony import */ var _StatsPicker_StatsPicker__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./StatsPicker/StatsPicker */ "./packages/grafana-ui/src/components/StatsPicker/StatsPicker.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StatsPicker", function() { return _StatsPicker_StatsPicker__WEBPACK_IMPORTED_MODULE_26__["StatsPicker"]; });

/* harmony import */ var _Input_Input__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Input/Input */ "./packages/grafana-ui/src/components/Input/Input.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Input", function() { return _Input_Input__WEBPACK_IMPORTED_MODULE_27__["Input"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputStatus", function() { return _Input_Input__WEBPACK_IMPORTED_MODULE_27__["InputStatus"]; });

/* harmony import */ var _RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./RefreshPicker/RefreshPicker */ "./packages/grafana-ui/src/components/RefreshPicker/RefreshPicker.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefreshPicker", function() { return _RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_28__["RefreshPicker"]; });

/* harmony import */ var _TimePicker_TimePicker__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./TimePicker/TimePicker */ "./packages/grafana-ui/src/components/TimePicker/TimePicker.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimePicker", function() { return _TimePicker_TimePicker__WEBPACK_IMPORTED_MODULE_29__["TimePicker"]; });

/* harmony import */ var _TimePicker_TimeOfDayPicker__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./TimePicker/TimeOfDayPicker */ "./packages/grafana-ui/src/components/TimePicker/TimeOfDayPicker.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeOfDayPicker", function() { return _TimePicker_TimeOfDayPicker__WEBPACK_IMPORTED_MODULE_30__["TimeOfDayPicker"]; });

/* harmony import */ var _List_List__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./List/List */ "./packages/grafana-ui/src/components/List/List.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "List", function() { return _List_List__WEBPACK_IMPORTED_MODULE_31__["List"]; });

/* harmony import */ var _SetInterval_SetInterval__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./SetInterval/SetInterval */ "./packages/grafana-ui/src/components/SetInterval/SetInterval.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetInterval", function() { return _SetInterval_SetInterval__WEBPACK_IMPORTED_MODULE_32__["SetInterval"]; });

/* harmony import */ var _Table_Table__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./Table/Table */ "./packages/grafana-ui/src/components/Table/Table.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Table", function() { return _Table_Table__WEBPACK_IMPORTED_MODULE_33__["Table"]; });

/* harmony import */ var _Table_TableInputCSV__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./Table/TableInputCSV */ "./packages/grafana-ui/src/components/Table/TableInputCSV.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TableInputCSV", function() { return _Table_TableInputCSV__WEBPACK_IMPORTED_MODULE_34__["TableInputCSV"]; });

/* harmony import */ var _BigValue_BigValue__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./BigValue/BigValue */ "./packages/grafana-ui/src/components/BigValue/BigValue.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BigValue", function() { return _BigValue_BigValue__WEBPACK_IMPORTED_MODULE_35__["BigValue"]; });

/* harmony import */ var _Gauge_Gauge__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Gauge/Gauge */ "./packages/grafana-ui/src/components/Gauge/Gauge.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gauge", function() { return _Gauge_Gauge__WEBPACK_IMPORTED_MODULE_36__["Gauge"]; });

/* harmony import */ var _Graph_Graph__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./Graph/Graph */ "./packages/grafana-ui/src/components/Graph/Graph.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Graph", function() { return _Graph_Graph__WEBPACK_IMPORTED_MODULE_37__["Graph"]; });

/* harmony import */ var _Graph_GraphLegend__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./Graph/GraphLegend */ "./packages/grafana-ui/src/components/Graph/GraphLegend.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphLegend", function() { return _Graph_GraphLegend__WEBPACK_IMPORTED_MODULE_38__["GraphLegend"]; });

/* harmony import */ var _Graph_GraphWithLegend__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./Graph/GraphWithLegend */ "./packages/grafana-ui/src/components/Graph/GraphWithLegend.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphWithLegend", function() { return _Graph_GraphWithLegend__WEBPACK_IMPORTED_MODULE_39__["GraphWithLegend"]; });

/* harmony import */ var _BarGauge_BarGauge__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./BarGauge/BarGauge */ "./packages/grafana-ui/src/components/BarGauge/BarGauge.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BarGauge", function() { return _BarGauge_BarGauge__WEBPACK_IMPORTED_MODULE_40__["BarGauge"]; });

/* harmony import */ var _VizRepeater_VizRepeater__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./VizRepeater/VizRepeater */ "./packages/grafana-ui/src/components/VizRepeater/VizRepeater.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VizRepeater", function() { return _VizRepeater_VizRepeater__WEBPACK_IMPORTED_MODULE_41__["VizRepeater"]; });

/* harmony import */ var _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./Legend/Legend */ "./packages/grafana-ui/src/components/Legend/Legend.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendOptions", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendBasicOptions", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendBasicOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendRenderOptions", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendRenderOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendList", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendList"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendTable", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendTable"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendItem", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendItem"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendPlacement", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendPlacement"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendDisplayMode", function() { return _Legend_Legend__WEBPACK_IMPORTED_MODULE_42__["LegendDisplayMode"]; });

/* harmony import */ var _Alert_Alert__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./Alert/Alert */ "./packages/grafana-ui/src/components/Alert/Alert.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Alert", function() { return _Alert_Alert__WEBPACK_IMPORTED_MODULE_43__["Alert"]; });

/* harmony import */ var _Graph_GraphSeriesToggler__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./Graph/GraphSeriesToggler */ "./packages/grafana-ui/src/components/Graph/GraphSeriesToggler.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphSeriesToggler", function() { return _Graph_GraphSeriesToggler__WEBPACK_IMPORTED_MODULE_44__["GraphSeriesToggler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphSeriesTogglerAPI", function() { return _Graph_GraphSeriesToggler__WEBPACK_IMPORTED_MODULE_44__["GraphSeriesTogglerAPI"]; });

/* harmony import */ var _Collapse_Collapse__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./Collapse/Collapse */ "./packages/grafana-ui/src/components/Collapse/Collapse.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collapse", function() { return _Collapse_Collapse__WEBPACK_IMPORTED_MODULE_45__["Collapse"]; });

/* harmony import */ var _Logs_LogLabels__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./Logs/LogLabels */ "./packages/grafana-ui/src/components/Logs/LogLabels.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLabels", function() { return _Logs_LogLabels__WEBPACK_IMPORTED_MODULE_46__["LogLabels"]; });

/* harmony import */ var _Logs_LogRows__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./Logs/LogRows */ "./packages/grafana-ui/src/components/Logs/LogRows.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogRows", function() { return _Logs_LogRows__WEBPACK_IMPORTED_MODULE_47__["LogRows"]; });

/* harmony import */ var _Logs_getLogRowStyles__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./Logs/getLogRowStyles */ "./packages/grafana-ui/src/components/Logs/getLogRowStyles.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLogRowStyles", function() { return _Logs_getLogRowStyles__WEBPACK_IMPORTED_MODULE_48__["getLogRowStyles"]; });

/* harmony import */ var _ToggleButtonGroup_ToggleButtonGroup__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./ToggleButtonGroup/ToggleButtonGroup */ "./packages/grafana-ui/src/components/ToggleButtonGroup/ToggleButtonGroup.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToggleButtonGroup", function() { return _ToggleButtonGroup_ToggleButtonGroup__WEBPACK_IMPORTED_MODULE_49__["ToggleButtonGroup"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToggleButton", function() { return _ToggleButtonGroup_ToggleButtonGroup__WEBPACK_IMPORTED_MODULE_49__["ToggleButton"]; });

/* harmony import */ var _ThresholdsEditor_ThresholdsEditor__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./ThresholdsEditor/ThresholdsEditor */ "./packages/grafana-ui/src/components/ThresholdsEditor/ThresholdsEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThresholdsEditor", function() { return _ThresholdsEditor_ThresholdsEditor__WEBPACK_IMPORTED_MODULE_50__["ThresholdsEditor"]; });

/* harmony import */ var _ClickOutsideWrapper_ClickOutsideWrapper__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./ClickOutsideWrapper/ClickOutsideWrapper */ "./packages/grafana-ui/src/components/ClickOutsideWrapper/ClickOutsideWrapper.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClickOutsideWrapper", function() { return _ClickOutsideWrapper_ClickOutsideWrapper__WEBPACK_IMPORTED_MODULE_51__["ClickOutsideWrapper"]; });

/* harmony import */ var _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ./SingleStatShared/index */ "./packages/grafana-ui/src/components/SingleStatShared/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldDisplayEditor", function() { return _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__["FieldDisplayEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldPropertiesEditor", function() { return _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__["FieldPropertiesEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SingleStatBaseOptions", function() { return _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__["SingleStatBaseOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatPanelChangedHandler", function() { return _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__["sharedSingleStatPanelChangedHandler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatMigrationHandler", function() { return _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__["sharedSingleStatMigrationHandler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "convertOldAngulrValueMapping", function() { return _SingleStatShared_index__WEBPACK_IMPORTED_MODULE_52__["convertOldAngulrValueMapping"]; });

/* harmony import */ var _CallToActionCard_CallToActionCard__WEBPACK_IMPORTED_MODULE_53__ = __webpack_require__(/*! ./CallToActionCard/CallToActionCard */ "./packages/grafana-ui/src/components/CallToActionCard/CallToActionCard.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CallToActionCard", function() { return _CallToActionCard_CallToActionCard__WEBPACK_IMPORTED_MODULE_53__["CallToActionCard"]; });

/* harmony import */ var _ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_54__ = __webpack_require__(/*! ./ContextMenu/ContextMenu */ "./packages/grafana-ui/src/components/ContextMenu/ContextMenu.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenu", function() { return _ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_54__["ContextMenu"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenuItem", function() { return _ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_54__["ContextMenuItem"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenuGroup", function() { return _ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_54__["ContextMenuGroup"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenuProps", function() { return _ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_54__["ContextMenuProps"]; });

/* harmony import */ var _DataLinks_DataLinkSuggestions__WEBPACK_IMPORTED_MODULE_55__ = __webpack_require__(/*! ./DataLinks/DataLinkSuggestions */ "./packages/grafana-ui/src/components/DataLinks/DataLinkSuggestions.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VariableSuggestion", function() { return _DataLinks_DataLinkSuggestions__WEBPACK_IMPORTED_MODULE_55__["VariableSuggestion"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VariableOrigin", function() { return _DataLinks_DataLinkSuggestions__WEBPACK_IMPORTED_MODULE_55__["VariableOrigin"]; });

/* harmony import */ var _DataLinks_DataLinksEditor__WEBPACK_IMPORTED_MODULE_56__ = __webpack_require__(/*! ./DataLinks/DataLinksEditor */ "./packages/grafana-ui/src/components/DataLinks/DataLinksEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataLinksEditor", function() { return _DataLinks_DataLinksEditor__WEBPACK_IMPORTED_MODULE_56__["DataLinksEditor"]; });

/* harmony import */ var _DataLinks_DataLinksContextMenu__WEBPACK_IMPORTED_MODULE_57__ = __webpack_require__(/*! ./DataLinks/DataLinksContextMenu */ "./packages/grafana-ui/src/components/DataLinks/DataLinksContextMenu.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataLinksContextMenu", function() { return _DataLinks_DataLinksContextMenu__WEBPACK_IMPORTED_MODULE_57__["DataLinksContextMenu"]; });

/* harmony import */ var _Legend_SeriesIcon__WEBPACK_IMPORTED_MODULE_58__ = __webpack_require__(/*! ./Legend/SeriesIcon */ "./packages/grafana-ui/src/components/Legend/SeriesIcon.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesIcon", function() { return _Legend_SeriesIcon__WEBPACK_IMPORTED_MODULE_58__["SeriesIcon"]; });

/* harmony import */ var _TransformersUI_transformers__WEBPACK_IMPORTED_MODULE_59__ = __webpack_require__(/*! ./TransformersUI/transformers */ "./packages/grafana-ui/src/components/TransformersUI/transformers.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformersUIRegistry", function() { return _TransformersUI_transformers__WEBPACK_IMPORTED_MODULE_59__["transformersUIRegistry"]; });

/* harmony import */ var _TransformersUI_TransformationRow__WEBPACK_IMPORTED_MODULE_60__ = __webpack_require__(/*! ./TransformersUI/TransformationRow */ "./packages/grafana-ui/src/components/TransformersUI/TransformationRow.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformationRow", function() { return _TransformersUI_TransformationRow__WEBPACK_IMPORTED_MODULE_60__["TransformationRow"]; });

/* harmony import */ var _TransformersUI_TransformationsEditor__WEBPACK_IMPORTED_MODULE_61__ = __webpack_require__(/*! ./TransformersUI/TransformationsEditor */ "./packages/grafana-ui/src/components/TransformersUI/TransformationsEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformationsEditor", function() { return _TransformersUI_TransformationsEditor__WEBPACK_IMPORTED_MODULE_61__["TransformationsEditor"]; });

/* harmony import */ var _JSONFormatter_JSONFormatter__WEBPACK_IMPORTED_MODULE_62__ = __webpack_require__(/*! ./JSONFormatter/JSONFormatter */ "./packages/grafana-ui/src/components/JSONFormatter/JSONFormatter.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JSONFormatter", function() { return _JSONFormatter_JSONFormatter__WEBPACK_IMPORTED_MODULE_62__["JSONFormatter"]; });

/* harmony import */ var _JSONFormatter_json_explorer_json_explorer__WEBPACK_IMPORTED_MODULE_63__ = __webpack_require__(/*! ./JSONFormatter/json_explorer/json_explorer */ "./packages/grafana-ui/src/components/JSONFormatter/json_explorer/json_explorer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonExplorer", function() { return _JSONFormatter_json_explorer_json_explorer__WEBPACK_IMPORTED_MODULE_63__["JsonExplorer"]; });

/* harmony import */ var _ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_64__ = __webpack_require__(/*! ./ErrorBoundary/ErrorBoundary */ "./packages/grafana-ui/src/components/ErrorBoundary/ErrorBoundary.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundary", function() { return _ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_64__["ErrorBoundary"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundaryAlert", function() { return _ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_64__["ErrorBoundaryAlert"]; });

/* harmony import */ var _AlphaNotice_AlphaNotice__WEBPACK_IMPORTED_MODULE_65__ = __webpack_require__(/*! ./AlphaNotice/AlphaNotice */ "./packages/grafana-ui/src/components/AlphaNotice/AlphaNotice.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaNotice", function() { return _AlphaNotice_AlphaNotice__WEBPACK_IMPORTED_MODULE_65__["AlphaNotice"]; });









// Select





// Forms



















// Renderless



// Visualizations















// Panel editors


















/***/ }),

/***/ "./packages/grafana-ui/src/index.ts":
/*!******************************************!*\
  !*** ./packages/grafana-ui/src/index.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _components__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components */ "./packages/grafana-ui/src/components/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeleteButton", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["DeleteButton"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tooltip", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Tooltip"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PopoverContent", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["PopoverContent"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PopoverController", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["PopoverController"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Popover", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Popover"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Portal", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Portal"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomScrollbar", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["CustomScrollbar"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Button"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinkButton", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LinkButton"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ButtonVariant", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ButtonVariant"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Select", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Select"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncSelect", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["AsyncSelect"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IndicatorsContainer", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["IndicatorsContainer"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoOptionsMessage", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["NoOptionsMessage"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "resetSelectStyles", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["resetSelectStyles"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ButtonSelect", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ButtonSelect"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormLabel", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["FormLabel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormField", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["FormField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SecretFormField", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SecretFormField"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoadingPlaceholder", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LoadingPlaceholder"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ColorPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SeriesColorPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPickerPopover", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SeriesColorPickerPopover"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesColorPickerPopoverWithTheme", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SeriesColorPickerPopoverWithTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelOptionsGroup", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["PanelOptionsGroup"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelOptionsGrid", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["PanelOptionsGrid"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueMappingsEditor", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ValueMappingsEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Switch", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Switch"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EmptySearchResult", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["EmptySearchResult"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PieChart", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["PieChart"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PieChartType", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["PieChartType"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnitPicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["UnitPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StatsPicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["StatsPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Input", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Input"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputStatus", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["InputStatus"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefreshPicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["RefreshPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimePicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["TimePicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeOfDayPicker", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["TimeOfDayPicker"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "List", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["List"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetInterval", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SetInterval"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Table", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Table"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TableInputCSV", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["TableInputCSV"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BigValue", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["BigValue"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gauge", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Gauge"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Graph", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Graph"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphLegend", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["GraphLegend"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphWithLegend", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["GraphWithLegend"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BarGauge", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["BarGauge"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VizRepeater", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["VizRepeater"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendOptions", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendBasicOptions", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendBasicOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendRenderOptions", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendRenderOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendList", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendList"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendTable", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendTable"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendItem", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendItem"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendPlacement", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendPlacement"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LegendDisplayMode", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LegendDisplayMode"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Alert", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Alert"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphSeriesToggler", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["GraphSeriesToggler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GraphSeriesTogglerAPI", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["GraphSeriesTogglerAPI"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collapse", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["Collapse"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogLabels", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LogLabels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LogRows", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["LogRows"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getLogRowStyles", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["getLogRowStyles"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToggleButtonGroup", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ToggleButtonGroup"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToggleButton", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ToggleButton"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThresholdsEditor", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ThresholdsEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClickOutsideWrapper", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ClickOutsideWrapper"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldDisplayEditor", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["FieldDisplayEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FieldPropertiesEditor", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["FieldPropertiesEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SingleStatBaseOptions", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SingleStatBaseOptions"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatPanelChangedHandler", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatPanelChangedHandler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sharedSingleStatMigrationHandler", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatMigrationHandler"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "convertOldAngulrValueMapping", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["convertOldAngulrValueMapping"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CallToActionCard", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["CallToActionCard"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenu", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ContextMenu"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenuItem", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ContextMenuItem"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenuGroup", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ContextMenuGroup"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContextMenuProps", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ContextMenuProps"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VariableSuggestion", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["VariableSuggestion"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VariableOrigin", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["VariableOrigin"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataLinksEditor", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["DataLinksEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataLinksContextMenu", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["DataLinksContextMenu"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SeriesIcon", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["SeriesIcon"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "transformersUIRegistry", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["transformersUIRegistry"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformationRow", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["TransformationRow"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformationsEditor", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["TransformationsEditor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JSONFormatter", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["JSONFormatter"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonExplorer", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["JsonExplorer"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundary", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ErrorBoundary"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundaryAlert", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["ErrorBoundaryAlert"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaNotice", function() { return _components__WEBPACK_IMPORTED_MODULE_0__["AlphaNotice"]; });

/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types */ "./packages/grafana-ui/src/types/index.ts");
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _types__WEBPACK_IMPORTED_MODULE_1__) if(["DeleteButton","Tooltip","PopoverContent","PopoverController","Popover","Portal","CustomScrollbar","Button","LinkButton","ButtonVariant","Select","AsyncSelect","IndicatorsContainer","NoOptionsMessage","resetSelectStyles","ButtonSelect","FormLabel","FormField","SecretFormField","LoadingPlaceholder","ColorPicker","SeriesColorPicker","SeriesColorPickerPopover","SeriesColorPickerPopoverWithTheme","PanelOptionsGroup","PanelOptionsGrid","ValueMappingsEditor","Switch","EmptySearchResult","PieChart","PieChartType","UnitPicker","StatsPicker","Input","InputStatus","RefreshPicker","TimePicker","TimeOfDayPicker","List","SetInterval","Table","TableInputCSV","BigValue","Gauge","Graph","GraphLegend","GraphWithLegend","BarGauge","VizRepeater","LegendOptions","LegendBasicOptions","LegendRenderOptions","LegendList","LegendTable","LegendItem","LegendPlacement","LegendDisplayMode","Alert","GraphSeriesToggler","GraphSeriesTogglerAPI","Collapse","LogLabels","LogRows","getLogRowStyles","ToggleButtonGroup","ToggleButton","ThresholdsEditor","ClickOutsideWrapper","FieldDisplayEditor","FieldPropertiesEditor","SingleStatBaseOptions","sharedSingleStatPanelChangedHandler","sharedSingleStatMigrationHandler","convertOldAngulrValueMapping","CallToActionCard","ContextMenu","ContextMenuItem","ContextMenuGroup","ContextMenuProps","VariableSuggestion","VariableOrigin","DataLinksEditor","DataLinksContextMenu","SeriesIcon","transformersUIRegistry","TransformationRow","TransformationsEditor","JSONFormatter","JsonExplorer","ErrorBoundary","ErrorBoundaryAlert","AlphaNotice","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _types__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils */ "./packages/grafana-ui/src/utils/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFixed", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["toFixed"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFixedScaled", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["toFixedScaled"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFixedUnit", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["toFixedUnit"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scaledUnits", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["scaledUnits"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "locale", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["locale"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "simpleCountUnit", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["simpleCountUnit"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getValueFormat", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getValueFormat"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getValueFormatterIndex", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getValueFormatterIndex"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getValueFormats", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getValueFormats"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PALETTE_ROWS", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["PALETTE_ROWS"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PALETTE_COLUMNS", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["PALETTE_COLUMNS"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_ANNOTATION_COLOR", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["DEFAULT_ANNOTATION_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OK_COLOR", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["OK_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ALERTING_COLOR", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["ALERTING_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NO_DATA_COLOR", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["NO_DATA_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PENDING_COLOR", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["PENDING_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "REGION_FILL_ALPHA", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["REGION_FILL_ALPHA"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "colors", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["colors"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sortedColors", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["sortedColors"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorDefinitionByName", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorDefinitionByName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorDefinition", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorDefinition"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorName", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorByName", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorByName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorFromHexRgbOrName", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorFromHexRgbOrName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorForTheme", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorForTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getNamedColorPalette", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getNamedColorPalette"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDisplayProcessor", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getDisplayProcessor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorFromThreshold", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getColorFromThreshold"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDecimalsForValue", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getDecimalsForValue"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_SERIES_NAME", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["VAR_SERIES_NAME"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_FIELD_NAME", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["VAR_FIELD_NAME"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_CALC", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["VAR_CALC"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_CELL_PREFIX", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["VAR_CELL_PREFIX"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_FIELD_DISPLAY_VALUES_LIMIT", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["DEFAULT_FIELD_DISPLAY_VALUES_LIMIT"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFieldDisplayValues", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getFieldDisplayValues"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "applyFieldProperties", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["applyFieldProperties"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFieldProperties", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getFieldProperties"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventsWithValidation", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["EventsWithValidation"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "validate", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["validate"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasValidationEvent", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["hasValidationEvent"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFlotPairs", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getFlotPairs"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFlotPairsConstant", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["getFlotPairsConstant"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SCHEMA", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["SCHEMA"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "makeFragment", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["makeFragment"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "makeValue", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["makeValue"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataLinkBuiltInVars", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["DataLinkBuiltInVars"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "linkModelToContextMenuItems", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["linkModelToContextMenuItems"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ansicolor", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["ansicolor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DOMUtil", function() { return _utils__WEBPACK_IMPORTED_MODULE_2__["DOMUtil"]; });

/* harmony import */ var _themes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./themes */ "./packages/grafana-ui/src/themes/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stylesFactory", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["stylesFactory"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThemeContext", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "withTheme", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["withTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mockTheme", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["mockTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTheme", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["getTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "selectThemeVariant", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["selectThemeVariant"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "useTheme", function() { return _themes__WEBPACK_IMPORTED_MODULE_3__["useTheme"]; });

/* harmony import */ var _slate_plugins__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./slate-plugins */ "./packages/grafana-ui/src/slate-plugins/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SlatePrism", function() { return _slate_plugins__WEBPACK_IMPORTED_MODULE_4__["SlatePrism"]; });








/***/ }),

/***/ "./packages/grafana-ui/src/slate-plugins/index.ts":
/*!********************************************************!*\
  !*** ./packages/grafana-ui/src/slate-plugins/index.ts ***!
  \********************************************************/
/*! exports provided: SlatePrism */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _slate_prism__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./slate-prism */ "./packages/grafana-ui/src/slate-plugins/slate-prism/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SlatePrism", function() { return _slate_prism__WEBPACK_IMPORTED_MODULE_0__["SlatePrism"]; });




/***/ }),

/***/ "./packages/grafana-ui/src/slate-plugins/slate-prism/TOKEN_MARK.ts":
/*!*************************************************************************!*\
  !*** ./packages/grafana-ui/src/slate-plugins/slate-prism/TOKEN_MARK.ts ***!
  \*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var TOKEN_MARK = 'prism-token';
/* harmony default export */ __webpack_exports__["default"] = (TOKEN_MARK);


/***/ }),

/***/ "./packages/grafana-ui/src/slate-plugins/slate-prism/index.ts":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/slate-plugins/slate-prism/index.ts ***!
  \********************************************************************/
/*! exports provided: SlatePrism */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SlatePrism", function() { return SlatePrism; });
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! prismjs */ "./node_modules/prismjs/prism.js");
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(prismjs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var slate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! slate */ "./node_modules/slate/lib/slate.es.js");
/* harmony import */ var _options__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./options */ "./packages/grafana-ui/src/slate-plugins/slate-prism/options.tsx");
/* harmony import */ var _TOKEN_MARK__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./TOKEN_MARK */ "./packages/grafana-ui/src/slate-plugins/slate-prism/TOKEN_MARK.ts");




/**
 * A Slate plugin to highlight code syntax.
 */
function SlatePrism(optsParam) {
    if (optsParam === void 0) { optsParam = {}; }
    var opts = new _options__WEBPACK_IMPORTED_MODULE_2__["default"](optsParam);
    return {
        decorateNode: function (node, editor, next) {
            if (!opts.onlyIn(node)) {
                return next();
            }
            return decorateNode(opts, slate__WEBPACK_IMPORTED_MODULE_1__["Block"].create(node));
        },
        renderDecoration: function (props, editor, next) {
            return opts.renderDecoration({
                children: props.children,
                decoration: props.decoration,
            }, editor, next);
        },
    };
}
/**
 * Returns the decoration for a node
 */
function decorateNode(opts, block) {
    var grammarName = opts.getSyntax(block);
    var grammar = prismjs__WEBPACK_IMPORTED_MODULE_0___default.a.languages[grammarName];
    if (!grammar) {
        // Grammar not loaded
        return [];
    }
    // Tokenize the whole block text
    var texts = block.getTexts();
    var blockText = texts.map(function (text) { return text && text.getText(); }).join('\n');
    var tokens = prismjs__WEBPACK_IMPORTED_MODULE_0___default.a.tokenize(blockText, grammar);
    // The list of decorations to return
    var decorations = [];
    var textStart = 0;
    var textEnd = 0;
    texts.forEach(function (text) {
        textEnd = textStart + text.getText().length;
        var offset = 0;
        function processToken(token, accu) {
            if (typeof token === 'string') {
                if (accu) {
                    var decoration = createDecoration({
                        text: text,
                        textStart: textStart,
                        textEnd: textEnd,
                        start: offset,
                        end: offset + token.length,
                        className: "prism-token token " + accu,
                        block: block,
                    });
                    if (decoration) {
                        decorations.push(decoration);
                    }
                }
                offset += token.length;
            }
            else {
                accu = accu + " " + token.type + " " + (token.alias || '');
                if (typeof token.content === 'string') {
                    var decoration = createDecoration({
                        text: text,
                        textStart: textStart,
                        textEnd: textEnd,
                        start: offset,
                        end: offset + token.content.length,
                        className: "prism-token token " + accu,
                        block: block,
                    });
                    if (decoration) {
                        decorations.push(decoration);
                    }
                    offset += token.content.length;
                }
                else {
                    // When using token.content instead of token.matchedStr, token can be deep
                    for (var i = 0; i < token.content.length; i += 1) {
                        // @ts-ignore
                        processToken(token.content[i], accu);
                    }
                }
            }
        }
        tokens.forEach(processToken);
        textStart = textEnd + 1; // account for added `\n`
    });
    return decorations;
}
/**
 * Return a decoration range for the given text.
 */
function createDecoration(_a) {
    var text = _a.text, textStart = _a.textStart, textEnd = _a.textEnd, start = _a.start, end = _a.end, className = _a.className, block = _a.block;
    if (start >= textEnd || end <= textStart) {
        // Ignore, the token is not in the text
        return null;
    }
    // Shrink to this text boundaries
    start = Math.max(start, textStart);
    end = Math.min(end, textEnd);
    // Now shift offsets to be relative to this text
    start -= textStart;
    end -= textStart;
    var myDec = block.createDecoration({
        object: 'decoration',
        anchor: {
            key: text.key,
            offset: start,
            object: 'point',
        },
        focus: {
            key: text.key,
            offset: end,
            object: 'point',
        },
        type: _TOKEN_MARK__WEBPACK_IMPORTED_MODULE_3__["default"],
        data: { className: className },
    });
    return myDec;
}


/***/ }),

/***/ "./packages/grafana-ui/src/slate-plugins/slate-prism/options.tsx":
/*!***********************************************************************!*\
  !*** ./packages/grafana-ui/src/slate-plugins/slate-prism/options.tsx ***!
  \***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! immutable */ "./node_modules/immutable/dist/immutable.js");
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(immutable__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _TOKEN_MARK__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./TOKEN_MARK */ "./packages/grafana-ui/src/slate-plugins/slate-prism/TOKEN_MARK.ts");




/**
 * Default filter for code blocks
 */
function defaultOnlyIn(node) {
    return node.object === 'block' && node.type === 'code_block';
}
/**
 * Default getter for syntax
 */
function defaultGetSyntax(node) {
    return 'javascript';
}
/**
 * Default rendering for decorations
 */
function defaultRenderDecoration(props, editor, next) {
    var decoration = props.decoration;
    if (decoration.type !== _TOKEN_MARK__WEBPACK_IMPORTED_MODULE_3__["default"]) {
        return next();
    }
    var className = decoration.data.get('className');
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: className }, props.children);
}
/**
 * The plugin options
 */
var Options = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Options, _super);
    function Options(props) {
        return _super.call(this, props) || this;
    }
    return Options;
}(Object(immutable__WEBPACK_IMPORTED_MODULE_2__["Record"])({
    onlyIn: defaultOnlyIn,
    getSyntax: defaultGetSyntax,
    renderDecoration: defaultRenderDecoration,
})));
/* harmony default export */ __webpack_exports__["default"] = (Options);


/***/ }),

/***/ "./packages/grafana-ui/src/themes/ThemeContext.tsx":
/*!*********************************************************!*\
  !*** ./packages/grafana-ui/src/themes/ThemeContext.tsx ***!
  \*********************************************************/
/*! exports provided: ThemeContext, withTheme, useTheme */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThemeContext", function() { return ThemeContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withTheme", function() { return withTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "useTheme", function() { return useTheme; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! hoist-non-react-statics */ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js");
/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _getTheme__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./getTheme */ "./packages/grafana-ui/src/themes/getTheme.ts");
/* harmony import */ var _types_theme__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../types/theme */ "./packages/grafana-ui/src/types/theme.ts");





// Use Grafana Dark theme by default
var ThemeContext = react__WEBPACK_IMPORTED_MODULE_1___default.a.createContext(Object(_getTheme__WEBPACK_IMPORTED_MODULE_3__["getTheme"])(_types_theme__WEBPACK_IMPORTED_MODULE_4__["GrafanaThemeType"].Dark));
var withTheme = function (Component) {
    var WithTheme = function (props) {
        // @ts-ignore
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ThemeContext.Consumer, null, function (theme) { return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Component, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { theme: theme })); });
    };
    WithTheme.displayName = "WithTheme(" + Component.displayName + ")";
    hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_2___default()(WithTheme, Component);
    return WithTheme;
};
function useTheme() {
    return Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(ThemeContext);
}


/***/ }),

/***/ "./packages/grafana-ui/src/themes/dark.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/themes/dark.ts ***!
  \************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./default */ "./packages/grafana-ui/src/themes/default.ts");
/* harmony import */ var _types_theme__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/theme */ "./packages/grafana-ui/src/types/theme.ts");



var basicColors = {
    black: '#000000',
    white: '#ffffff',
    dark1: '#141414',
    dark2: '#161719',
    dark3: '#1f1f20',
    dark4: '#212124',
    dark5: '#222426',
    dark6: '#262628',
    dark7: '#292a2d',
    dark8: '#2f2f32',
    dark9: '#343436',
    dark10: '#424345',
    gray1: '#555555',
    gray2: '#8e8e8e',
    gray3: '#b3b3b3',
    gray4: '#d8d9da',
    gray5: '#ececec',
    gray6: '#f4f5f8',
    gray7: '#fbfbfb',
    grayBlue: '#212327',
    blueBase: '#3274d9',
    blueShade: '#1f60c4',
    blueLight: '#5794f2',
    blueFaint: '#041126',
    redBase: '#e02f44',
    redShade: '#c4162a',
    greenBase: '#299c46',
    greenShade: '#23843b',
    blue: '#33b5e5',
    red: '#d44a3a',
    yellow: '#ecbb13',
    purple: '#9933cc',
    variable: '#32d1df',
    orange: '#eb7b18',
};
var darkTheme = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _default__WEBPACK_IMPORTED_MODULE_1__["default"], { type: _types_theme__WEBPACK_IMPORTED_MODULE_2__["GrafanaThemeType"].Dark, name: 'Grafana Dark', colors: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, basicColors, { inputBlack: '#09090b', brandPrimary: basicColors.orange, brandSuccess: basicColors.greenBase, brandWarning: basicColors.orange, brandDanger: basicColors.redBase, queryRed: basicColors.redBase, queryGreen: '#74e680', queryPurple: '#fe85fc', queryKeyword: '#66d9ef', queryOrange: basicColors.orange, online: basicColors.greenBase, warn: '#f79520', critical: basicColors.redBase, bodyBg: basicColors.dark2, pageBg: basicColors.dark2, body: basicColors.gray4, text: basicColors.gray4, textStrong: basicColors.white, textWeak: basicColors.gray2, textEmphasis: basicColors.gray5, textFaint: basicColors.dark5, link: basicColors.gray4, linkDisabled: basicColors.gray2, linkHover: basicColors.white, linkExternal: basicColors.blue, headingColor: basicColors.gray4 }), background: {
        dropdown: basicColors.dark3,
        scrollbar: basicColors.dark9,
        scrollbar2: basicColors.dark9,
    } });
/* harmony default export */ __webpack_exports__["default"] = (darkTheme);


/***/ }),

/***/ "./packages/grafana-ui/src/themes/default.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-ui/src/themes/default.ts ***!
  \***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var theme = {
    name: 'Grafana Default',
    typography: {
        fontFamily: {
            sansSerif: "'Roboto', 'Helvetica Neue', Arial, sans-serif",
            monospace: "Menlo, Monaco, Consolas, 'Courier New', monospace",
        },
        size: {
            root: '14px',
            base: '13px',
            xs: '10px',
            sm: '12px',
            md: '14px',
            lg: '18px',
        },
        heading: {
            h1: '28px',
            h2: '24px',
            h3: '21px',
            h4: '18px',
            h5: '16px',
            h6: '14px',
        },
        weight: {
            light: 300,
            regular: 400,
            semibold: 500,
        },
        lineHeight: {
            xs: 1,
            sm: 1.1,
            md: 4 / 3,
            lg: 1.5,
        },
        link: {
            decoration: 'none',
            hoverDecoration: 'none',
        },
    },
    breakpoints: {
        xs: '0',
        sm: '544px',
        md: '769px',
        lg: '992px',
        xl: '1200px',
    },
    spacing: {
        insetSquishMd: '4px 8px',
        d: '14px',
        xxs: '2px',
        xs: '4px',
        sm: '8px',
        md: '16px',
        lg: '24px',
        xl: '32px',
        gutter: '30px',
    },
    border: {
        radius: {
            sm: '2px',
            md: '3px',
            lg: '5px',
        },
        width: {
            sm: '1px',
        },
    },
    height: {
        sm: '24px',
        md: '32px',
        lg: '48px',
    },
    panelPadding: 8,
    panelHeaderHeight: 28,
    zIndex: {
        dropdown: '1000',
        navbarFixed: '1020',
        sidemenu: '1025',
        tooltip: '1030',
        modalBackdrop: '1040',
        modal: '1050',
        typeahead: '1060',
    },
};
/* harmony default export */ __webpack_exports__["default"] = (theme);


/***/ }),

/***/ "./packages/grafana-ui/src/themes/getTheme.ts":
/*!****************************************************!*\
  !*** ./packages/grafana-ui/src/themes/getTheme.ts ***!
  \****************************************************/
/*! exports provided: getTheme, mockTheme */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTheme", function() { return getTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mockTheme", function() { return mockTheme; });
/* harmony import */ var _dark__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dark */ "./packages/grafana-ui/src/themes/dark.ts");
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./light */ "./packages/grafana-ui/src/themes/light.ts");


var themeMock;
var getTheme = function (name) {
    return (themeMock && themeMock(name)) || (name === 'light' ? _light__WEBPACK_IMPORTED_MODULE_1__["default"] : _dark__WEBPACK_IMPORTED_MODULE_0__["default"]);
};
var mockTheme = function (mock) {
    themeMock = mock;
    return function () {
        themeMock = null;
    };
};


/***/ }),

/***/ "./packages/grafana-ui/src/themes/index.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-ui/src/themes/index.ts ***!
  \*************************************************/
/*! exports provided: stylesFactory, ThemeContext, withTheme, mockTheme, getTheme, selectThemeVariant, useTheme */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ThemeContext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ThemeContext */ "./packages/grafana-ui/src/themes/ThemeContext.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThemeContext", function() { return _ThemeContext__WEBPACK_IMPORTED_MODULE_0__["ThemeContext"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "withTheme", function() { return _ThemeContext__WEBPACK_IMPORTED_MODULE_0__["withTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "useTheme", function() { return _ThemeContext__WEBPACK_IMPORTED_MODULE_0__["useTheme"]; });

/* harmony import */ var _getTheme__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./getTheme */ "./packages/grafana-ui/src/themes/getTheme.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mockTheme", function() { return _getTheme__WEBPACK_IMPORTED_MODULE_1__["mockTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getTheme", function() { return _getTheme__WEBPACK_IMPORTED_MODULE_1__["getTheme"]; });

/* harmony import */ var _selectThemeVariant__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./selectThemeVariant */ "./packages/grafana-ui/src/themes/selectThemeVariant.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "selectThemeVariant", function() { return _selectThemeVariant__WEBPACK_IMPORTED_MODULE_2__["selectThemeVariant"]; });

/* harmony import */ var _stylesFactory__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./stylesFactory */ "./packages/grafana-ui/src/themes/stylesFactory.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stylesFactory", function() { return _stylesFactory__WEBPACK_IMPORTED_MODULE_3__["stylesFactory"]; });








/***/ }),

/***/ "./packages/grafana-ui/src/themes/light.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-ui/src/themes/light.ts ***!
  \*************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _default__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./default */ "./packages/grafana-ui/src/themes/default.ts");
/* harmony import */ var _types_theme__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/theme */ "./packages/grafana-ui/src/types/theme.ts");



var basicColors = {
    black: '#000000',
    white: '#ffffff',
    dark1: '#1e2028',
    dark2: '#41444b',
    dark3: '#303133',
    dark4: '#35373f',
    dark5: '#41444b',
    dark6: '#41444b',
    dark7: '#41444b',
    dark8: '#2f2f32',
    dark9: '#343436',
    dark10: '#424345',
    gray1: '#52545c',
    gray2: '#767980',
    gray3: '#acb6bf',
    gray4: '#c7d0d9',
    gray5: '#dde4ed',
    gray6: '#e9edf2',
    gray7: '#f7f8fa',
    grayBlue: '#212327',
    blueBase: '#3274d9',
    blueShade: '#1f60c4',
    blueLight: '#5794f2',
    blueFaint: '#f5f9ff',
    redBase: '#e02f44',
    redShade: '#c4162a',
    greenBase: '#3eb15b',
    greenShade: '#369b4f',
    blue: '#0083b3',
    red: '#d44939',
    yellow: '#ff851b',
    purple: '#9954bb',
    variable: '#007580',
    orange: '#ff7941',
};
var lightTheme = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _default__WEBPACK_IMPORTED_MODULE_1__["default"], { type: _types_theme__WEBPACK_IMPORTED_MODULE_2__["GrafanaThemeType"].Light, name: 'Grafana Light', colors: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, basicColors, { variable: basicColors.blue, inputBlack: '#09090b', brandPrimary: basicColors.orange, brandSuccess: basicColors.greenBase, brandWarning: basicColors.orange, brandDanger: basicColors.redBase, queryRed: basicColors.redBase, queryGreen: basicColors.greenBase, queryPurple: basicColors.purple, queryKeyword: basicColors.blueBase, queryOrange: basicColors.orange, online: basicColors.greenShade, warn: '#f79520', critical: basicColors.redShade, bodyBg: basicColors.gray7, pageBg: basicColors.gray7, body: basicColors.gray1, text: basicColors.gray1, textStrong: basicColors.dark2, textWeak: basicColors.gray2, textEmphasis: basicColors.dark5, textFaint: basicColors.dark4, link: basicColors.gray1, linkDisabled: basicColors.gray3, linkHover: basicColors.dark1, linkExternal: basicColors.blueLight, headingColor: basicColors.gray1 }), background: {
        dropdown: basicColors.white,
        scrollbar: basicColors.gray5,
        scrollbar2: basicColors.gray5,
    } });
/* harmony default export */ __webpack_exports__["default"] = (lightTheme);


/***/ }),

/***/ "./packages/grafana-ui/src/themes/selectThemeVariant.ts":
/*!**************************************************************!*\
  !*** ./packages/grafana-ui/src/themes/selectThemeVariant.ts ***!
  \**************************************************************/
/*! exports provided: selectThemeVariant */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectThemeVariant", function() { return selectThemeVariant; });
/* harmony import */ var _types_theme__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/theme */ "./packages/grafana-ui/src/types/theme.ts");

var selectThemeVariant = function (variants, currentTheme) {
    return variants[currentTheme || _types_theme__WEBPACK_IMPORTED_MODULE_0__["GrafanaThemeType"].Dark];
};


/***/ }),

/***/ "./packages/grafana-ui/src/themes/stylesFactory.ts":
/*!*********************************************************!*\
  !*** ./packages/grafana-ui/src/themes/stylesFactory.ts ***!
  \*********************************************************/
/*! exports provided: stylesFactory */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stylesFactory", function() { return stylesFactory; });
/* harmony import */ var memoize_one__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! memoize-one */ "./node_modules/memoize-one/dist/memoize-one.esm.js");

// import { KeyValue } from '@grafana/data';
/**
 *  Creates memoized version of styles creator
 * @param stylesCreator function accepting dependencies based on which styles are created
 */
function stylesFactory(stylesCreator) {
    return Object(memoize_one__WEBPACK_IMPORTED_MODULE_0__["default"])(stylesCreator);
}


/***/ }),

/***/ "./packages/grafana-ui/src/types/app.ts":
/*!**********************************************!*\
  !*** ./packages/grafana-ui/src/types/app.ts ***!
  \**********************************************/
/*! exports provided: AppPlugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppPlugin", function() { return AppPlugin; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _plugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./plugin */ "./packages/grafana-ui/src/types/plugin.ts");


var AppPlugin = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AppPlugin, _super);
    function AppPlugin() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Called after the module has loaded, and before the app is used.
     * This function may be called multiple times on the same instance.
     * The first time, `this.meta` will be undefined
     */
    AppPlugin.prototype.init = function (meta) { };
    /**
     * Set the component displayed under:
     *   /a/${plugin-id}/*
     */
    AppPlugin.prototype.setRootPage = function (root, rootNav) {
        this.root = root;
        this.rootNav = rootNav;
        return this;
    };
    AppPlugin.prototype.setComponentsFromLegacyExports = function (pluginExports) {
        var e_1, _a;
        if (pluginExports.ConfigCtrl) {
            this.angularConfigCtrl = pluginExports.ConfigCtrl;
        }
        if (this.meta && this.meta.includes) {
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.meta.includes), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var include = _c.value;
                    if (include.type === _plugin__WEBPACK_IMPORTED_MODULE_1__["PluginIncludeType"].page && include.component) {
                        var exp = pluginExports[include.component];
                        if (!exp) {
                            console.warn('App Page uses unknown component: ', include.component, this.meta);
                            continue;
                        }
                        if (!this.angularPages) {
                            this.angularPages = {};
                        }
                        this.angularPages[include.component] = exp;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
    };
    return AppPlugin;
}(_plugin__WEBPACK_IMPORTED_MODULE_1__["GrafanaPlugin"]));



/***/ }),

/***/ "./packages/grafana-ui/src/types/datasource.ts":
/*!*****************************************************!*\
  !*** ./packages/grafana-ui/src/types/datasource.ts ***!
  \*****************************************************/
/*! exports provided: DataSourcePlugin, DataSourceApi, DataSourceStatus */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataSourcePlugin", function() { return DataSourcePlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataSourceApi", function() { return DataSourceApi; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataSourceStatus", function() { return DataSourceStatus; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _plugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./plugin */ "./packages/grafana-ui/src/types/plugin.ts");


var DataSourcePlugin = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DataSourcePlugin, _super);
    function DataSourcePlugin(DataSourceClass) {
        var _this = _super.call(this) || this;
        _this.DataSourceClass = DataSourceClass;
        _this.components = {};
        return _this;
    }
    DataSourcePlugin.prototype.setConfigEditor = function (editor) {
        this.components.ConfigEditor = editor;
        return this;
    };
    DataSourcePlugin.prototype.setConfigCtrl = function (ConfigCtrl) {
        this.angularConfigCtrl = ConfigCtrl;
        return this;
    };
    DataSourcePlugin.prototype.setQueryCtrl = function (QueryCtrl) {
        this.components.QueryCtrl = QueryCtrl;
        return this;
    };
    DataSourcePlugin.prototype.setAnnotationQueryCtrl = function (AnnotationsQueryCtrl) {
        this.components.AnnotationsQueryCtrl = AnnotationsQueryCtrl;
        return this;
    };
    DataSourcePlugin.prototype.setQueryEditor = function (QueryEditor) {
        this.components.QueryEditor = QueryEditor;
        return this;
    };
    DataSourcePlugin.prototype.setExploreQueryField = function (ExploreQueryField) {
        this.components.ExploreQueryField = ExploreQueryField;
        return this;
    };
    DataSourcePlugin.prototype.setExploreMetricsQueryField = function (ExploreQueryField) {
        this.components.ExploreMetricsQueryField = ExploreQueryField;
        return this;
    };
    DataSourcePlugin.prototype.setExploreLogsQueryField = function (ExploreQueryField) {
        this.components.ExploreLogsQueryField = ExploreQueryField;
        return this;
    };
    DataSourcePlugin.prototype.setExploreStartPage = function (ExploreStartPage) {
        this.components.ExploreStartPage = ExploreStartPage;
        return this;
    };
    DataSourcePlugin.prototype.setVariableQueryEditor = function (VariableQueryEditor) {
        this.components.VariableQueryEditor = VariableQueryEditor;
        return this;
    };
    DataSourcePlugin.prototype.setComponentsFromLegacyExports = function (pluginExports) {
        this.angularConfigCtrl = pluginExports.ConfigCtrl;
        this.components.QueryCtrl = pluginExports.QueryCtrl;
        this.components.AnnotationsQueryCtrl = pluginExports.AnnotationsQueryCtrl;
        this.components.ExploreQueryField = pluginExports.ExploreQueryField;
        this.components.ExploreStartPage = pluginExports.ExploreStartPage;
        this.components.QueryEditor = pluginExports.QueryEditor;
        this.components.VariableQueryEditor = pluginExports.VariableQueryEditor;
    };
    return DataSourcePlugin;
}(_plugin__WEBPACK_IMPORTED_MODULE_1__["GrafanaPlugin"]));

/**
 * The main data source abstraction interface, represents an instance of a data source
 *
 * Although this is a class, datasource implementations do not *yet* need to extend it.
 * As such, we can not yet add functions with default implementations.
 */
var DataSourceApi = /** @class */ (function () {
    function DataSourceApi(instanceSettings) {
        this.name = instanceSettings.name;
        this.id = instanceSettings.id;
    }
    return DataSourceApi;
}());

var DataSourceStatus;
(function (DataSourceStatus) {
    DataSourceStatus[DataSourceStatus["Connected"] = 0] = "Connected";
    DataSourceStatus[DataSourceStatus["Disconnected"] = 1] = "Disconnected";
})(DataSourceStatus || (DataSourceStatus = {}));


/***/ }),

/***/ "./packages/grafana-ui/src/types/index.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/types/index.ts ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _panel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./panel */ "./packages/grafana-ui/src/types/panel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelPlugin", function() { return _panel__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VizOrientation", function() { return _panel__WEBPACK_IMPORTED_MODULE_0__["VizOrientation"]; });

/* harmony import */ var _plugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./plugin */ "./packages/grafana-ui/src/types/plugin.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PluginState", function() { return _plugin__WEBPACK_IMPORTED_MODULE_1__["PluginState"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PluginType", function() { return _plugin__WEBPACK_IMPORTED_MODULE_1__["PluginType"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PluginIncludeType", function() { return _plugin__WEBPACK_IMPORTED_MODULE_1__["PluginIncludeType"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GrafanaPlugin", function() { return _plugin__WEBPACK_IMPORTED_MODULE_1__["GrafanaPlugin"]; });

/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./app */ "./packages/grafana-ui/src/types/app.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AppPlugin", function() { return _app__WEBPACK_IMPORTED_MODULE_2__["AppPlugin"]; });

/* harmony import */ var _datasource__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./datasource */ "./packages/grafana-ui/src/types/datasource.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataSourcePlugin", function() { return _datasource__WEBPACK_IMPORTED_MODULE_3__["DataSourcePlugin"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataSourceApi", function() { return _datasource__WEBPACK_IMPORTED_MODULE_3__["DataSourceApi"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataSourceStatus", function() { return _datasource__WEBPACK_IMPORTED_MODULE_3__["DataSourceStatus"]; });

/* harmony import */ var _theme__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./theme */ "./packages/grafana-ui/src/types/theme.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GrafanaThemeType", function() { return _theme__WEBPACK_IMPORTED_MODULE_4__["GrafanaThemeType"]; });

/* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./input */ "./packages/grafana-ui/src/types/input.ts");
/* harmony import */ var _input__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_input__WEBPACK_IMPORTED_MODULE_5__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _input__WEBPACK_IMPORTED_MODULE_5__) if(["PanelPlugin","VizOrientation","PluginState","PluginType","PluginIncludeType","GrafanaPlugin","AppPlugin","DataSourcePlugin","DataSourceApi","DataSourceStatus","GrafanaThemeType","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _input__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__));








/***/ }),

/***/ "./packages/grafana-ui/src/types/input.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/types/input.ts ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./packages/grafana-ui/src/types/panel.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/types/panel.ts ***!
  \************************************************/
/*! exports provided: PanelPlugin, VizOrientation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelPlugin", function() { return PanelPlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VizOrientation", function() { return VizOrientation; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _plugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./plugin */ "./packages/grafana-ui/src/types/plugin.ts");


var PanelPlugin = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PanelPlugin, _super);
    function PanelPlugin(panel) {
        var _this = _super.call(this) || this;
        _this.panel = panel;
        return _this;
    }
    PanelPlugin.prototype.setEditor = function (editor) {
        this.editor = editor;
        return this;
    };
    PanelPlugin.prototype.setDefaults = function (defaults) {
        this.defaults = defaults;
        return this;
    };
    /**
     * This function is called before the panel first loads if
     * the current version is different than the version that was saved.
     *
     * This is a good place to support any changes to the options model
     */
    PanelPlugin.prototype.setMigrationHandler = function (handler) {
        this.onPanelMigration = handler;
        return this;
    };
    /**
     * This function is called when the visualization was changed.  This
     * passes in the options that were used in the previous visualization
     */
    PanelPlugin.prototype.setPanelChangeHandler = function (handler) {
        this.onPanelTypeChanged = handler;
        return this;
    };
    return PanelPlugin;
}(_plugin__WEBPACK_IMPORTED_MODULE_1__["GrafanaPlugin"]));

var VizOrientation;
(function (VizOrientation) {
    VizOrientation["Auto"] = "auto";
    VizOrientation["Vertical"] = "vertical";
    VizOrientation["Horizontal"] = "horizontal";
})(VizOrientation || (VizOrientation = {}));


/***/ }),

/***/ "./packages/grafana-ui/src/types/plugin.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-ui/src/types/plugin.ts ***!
  \*************************************************/
/*! exports provided: PluginState, PluginType, PluginIncludeType, GrafanaPlugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginState", function() { return PluginState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginType", function() { return PluginType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginIncludeType", function() { return PluginIncludeType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GrafanaPlugin", function() { return GrafanaPlugin; });
var PluginState;
(function (PluginState) {
    PluginState["alpha"] = "alpha";
    PluginState["beta"] = "beta";
})(PluginState || (PluginState = {}));
var PluginType;
(function (PluginType) {
    PluginType["panel"] = "panel";
    PluginType["datasource"] = "datasource";
    PluginType["app"] = "app";
    PluginType["renderer"] = "renderer";
})(PluginType || (PluginType = {}));
var PluginIncludeType;
(function (PluginIncludeType) {
    PluginIncludeType["dashboard"] = "dashboard";
    PluginIncludeType["page"] = "page";
    // Only valid for apps
    PluginIncludeType["panel"] = "panel";
    PluginIncludeType["datasource"] = "datasource";
})(PluginIncludeType || (PluginIncludeType = {}));
var GrafanaPlugin = /** @class */ (function () {
    function GrafanaPlugin() {
    }
    // Tabs on the plugin page
    GrafanaPlugin.prototype.addConfigPage = function (tab) {
        if (!this.configPages) {
            this.configPages = [];
        }
        this.configPages.push(tab);
        return this;
    };
    return GrafanaPlugin;
}());



/***/ }),

/***/ "./packages/grafana-ui/src/types/theme.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/types/theme.ts ***!
  \************************************************/
/*! exports provided: GrafanaThemeType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GrafanaThemeType", function() { return GrafanaThemeType; });
var GrafanaThemeType;
(function (GrafanaThemeType) {
    GrafanaThemeType["Light"] = "light";
    GrafanaThemeType["Dark"] = "dark";
})(GrafanaThemeType || (GrafanaThemeType = {}));


/***/ }),

/***/ "./packages/grafana-ui/src/utils/ansicolor.ts":
/*!****************************************************!*\
  !*** ./packages/grafana-ui/src/utils/ansicolor.ts ***!
  \****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
// Vendored and converted to TS, source: https://github.com/xpl/ansicolor/blob/b82360563ed29de444dc7618b9236191e0a77096/ansicolor.js
// License: Unlicense, author: https://github.com/xpl

var O = Object;
/*  See https://misc.flogisoft.com/bash/tip_colors_and_formatting
    ------------------------------------------------------------------------ */
var colorCodes = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'lightGray', '', 'default'], colorCodesLight = [
    'darkGray',
    'lightRed',
    'lightGreen',
    'lightYellow',
    'lightBlue',
    'lightMagenta',
    'lightCyan',
    'white',
    '',
], styleCodes = ['', 'bright', 'dim', 'italic', 'underline', '', '', 'inverse'], asBright = {
    red: 'lightRed',
    green: 'lightGreen',
    yellow: 'lightYellow',
    blue: 'lightBlue',
    magenta: 'lightMagenta',
    cyan: 'lightCyan',
    black: 'darkGray',
    lightGray: 'white',
}, types = {
    0: 'style',
    2: 'unstyle',
    3: 'color',
    9: 'colorLight',
    4: 'bgColor',
    10: 'bgColorLight',
}, subtypes = {
    color: colorCodes,
    colorLight: colorCodesLight,
    bgColor: colorCodes,
    bgColorLight: colorCodesLight,
    style: styleCodes,
    unstyle: styleCodes,
};
/*  ------------------------------------------------------------------------ */
var clean = function (obj) {
    for (var k in obj) {
        if (!obj[k]) {
            delete obj[k];
        }
    }
    return O.keys(obj).length === 0 ? undefined : obj;
};
/*  ------------------------------------------------------------------------ */
var Color = /** @class */ (function () {
    function Color(background, name, brightness) {
        this.background = background;
        this.name = name;
        this.brightness = brightness;
    }
    Object.defineProperty(Color.prototype, "inverse", {
        get: function () {
            return new Color(!this.background, this.name || (this.background ? 'black' : 'white'), this.brightness);
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Color.prototype, "clean", {
        get: function () {
            return clean({
                name: this.name === 'default' ? '' : this.name,
                bright: this.brightness === Code.bright,
                dim: this.brightness === Code.dim,
            });
        },
        enumerable: true,
        configurable: true
    });
    Color.prototype.defaultBrightness = function (value) {
        return new Color(this.background, this.name, this.brightness || value);
    };
    Color.prototype.css = function (inverted) {
        var color = inverted ? this.inverse : this;
        // @ts-ignore
        var rgbName = (color.brightness === Code.bright && asBright[color.name]) || color.name;
        var prop = color.background ? 'background:' : 'color:';
        // @ts-ignore
        var rgb = Colors.rgb[rgbName];
        var alpha = this.brightness === Code.dim ? 0.5 : 1;
        return rgb
            ? prop + 'rgba(' + tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](rgb, [alpha]).join(',') + ');'
            : !color.background && alpha < 1
                ? 'color:rgba(0,0,0,0.5);'
                : ''; // Chrome does not support 'opacity' property...
    };
    return Color;
}());
/*  ------------------------------------------------------------------------ */
var Code = /** @class */ (function () {
    function Code(n) {
        if (n !== undefined) {
            this.value = Number(n);
        }
        else {
            this.value = undefined;
        }
    }
    Object.defineProperty(Code.prototype, "type", {
        get: function () {
            // @ts-ignore
            return types[Math.floor(this.value / 10)];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Code.prototype, "subtype", {
        get: function () {
            // @ts-ignore
            return subtypes[this.type][this.value % 10];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Code.prototype, "str", {
        get: function () {
            return this.value ? '\u001b[' + this.value + 'm' : '';
        },
        enumerable: true,
        configurable: true
    });
    Code.str = function (x) {
        return new Code(x).str;
    };
    Object.defineProperty(Code.prototype, "isBrightness", {
        get: function () {
            return this.value === Code.noBrightness || this.value === Code.bright || this.value === Code.dim;
        },
        enumerable: true,
        configurable: true
    });
    Code.reset = 0;
    Code.bright = 1;
    Code.dim = 2;
    Code.inverse = 7;
    Code.noBrightness = 22;
    Code.noItalic = 23;
    Code.noUnderline = 24;
    Code.noInverse = 27;
    Code.noColor = 39;
    Code.noBgColor = 49;
    return Code;
}());
/*  ------------------------------------------------------------------------ */
var replaceAll = function (str, a, b) { return str.split(a).join(b); };
/*  ANSI brightness codes do not overlap, e.g. "{bright}{dim}foo" will be rendered bright (not dim).
    So we fix it by adding brightness canceling before each brightness code, so the former example gets
    converted to "{noBrightness}{bright}{noBrightness}{dim}foo" – this way it gets rendered as expected.
 */
var denormalizeBrightness = function (s) { return s.replace(/(\u001b\[(1|2)m)/g, '\u001b[22m$1'); };
var normalizeBrightness = function (s) { return s.replace(/\u001b\[22m(\u001b\[(1|2)m)/g, '$1'); };
// @ts-ignore
var wrap = function (x, openCode, closeCode) {
    var open = Code.str(openCode), close = Code.str(closeCode);
    return String(x)
        .split('\n')
        .map(function (line) { return denormalizeBrightness(open + replaceAll(normalizeBrightness(line), close, open) + close); })
        .join('\n');
};
/*  ------------------------------------------------------------------------ */
var camel = function (a, b) { return a + b.charAt(0).toUpperCase() + b.slice(1); };
var stringWrappingMethods = (function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](colorCodes.map(function (k, i) {
        return !k
            ? []
            : [
                // color methods
                [k, 30 + i, Code.noColor],
                [camel('bg', k), 40 + i, Code.noBgColor],
            ];
    }), colorCodesLight.map(function (k, i) {
        return !k
            ? []
            : [
                // light color methods
                [k, 90 + i, Code.noColor],
                [camel('bg', k), 100 + i, Code.noBgColor],
            ];
    }), ['', 'BrightRed', 'BrightGreen', 'BrightYellow', 'BrightBlue', 'BrightMagenta', 'BrightCyan'].map(function (k, i) {
        return !k ? [] : [['bg' + k, 100 + i, Code.noBgColor]];
    }), styleCodes.map(function (k, i) {
        return !k
            ? []
            : [
                // style methods
                [k, i, k === 'bright' || k === 'dim' ? Code.noBrightness : 20 + i],
            ];
    })).reduce(function (a, b) { return a.concat(b); });
})();
/*  ------------------------------------------------------------------------ */
// @ts-ignore
var assignStringWrappingAPI = function (target, wrapBefore) {
    if (wrapBefore === void 0) { wrapBefore = target; }
    return stringWrappingMethods.reduce(function (memo, _a) {
        var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](_a, 3), k = _b[0], open = _b[1], close = _b[2];
        return O.defineProperty(memo, k, {
            // @ts-ignore
            get: function () { return assignStringWrappingAPI(function (str) { return wrapBefore(wrap(str, open, close)); }); },
        });
    }, target);
};
/*  ------------------------------------------------------------------------ */
var TEXT = 0, BRACKET = 1, CODE = 2;
function rawParse(s) {
    var e_1, _a;
    var state = TEXT, buffer = '', text = '', code = '', codes = [];
    var spans = [];
    for (var i = 0, n = s.length; i < n; i++) {
        var c = s[i];
        buffer += c;
        switch (state) {
            case TEXT: {
                if (c === '\u001b') {
                    state = BRACKET;
                    buffer = c;
                }
                else {
                    text += c;
                }
                break;
            }
            case BRACKET:
                if (c === '[') {
                    state = CODE;
                    code = '';
                    codes = [];
                }
                else {
                    state = TEXT;
                    text += buffer;
                }
                break;
            case CODE:
                if (c >= '0' && c <= '9') {
                    code += c;
                }
                else if (c === ';') {
                    codes.push(new Code(code));
                    code = '';
                }
                else if (c === 'm' && code.length) {
                    codes.push(new Code(code));
                    try {
                        for (var codes_1 = (e_1 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](codes)), codes_1_1 = codes_1.next(); !codes_1_1.done; codes_1_1 = codes_1.next()) {
                            var code_1 = codes_1_1.value;
                            spans.push({ text: text, code: code_1 });
                            text = '';
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (codes_1_1 && !codes_1_1.done && (_a = codes_1.return)) _a.call(codes_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    state = TEXT;
                }
                else {
                    state = TEXT;
                    text += buffer;
                }
        }
    }
    if (state !== TEXT) {
        text += buffer;
    }
    if (text) {
        spans.push({ text: text, code: new Code() });
    }
    return spans;
}
/*  ------------------------------------------------------------------------ */
/**
 * Represents an ANSI-escaped string.
 */
var Colors = /** @class */ (function () {
    /**
     * @param {string} s a string containing ANSI escape codes.
     */
    function Colors(s) {
        this.spans = s ? rawParse(s) : [];
    }
    Object.defineProperty(Colors.prototype, "str", {
        get: function () {
            return this.spans.reduce(function (str, p) { return str + p.text + p.code.str; }, '');
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Colors.prototype, "parsed", {
        get: function () {
            var styles;
            var brightness;
            var color;
            var bgColor;
            function reset() {
                (color = new Color()),
                    (bgColor = new Color(true /* background */)),
                    (brightness = undefined),
                    (styles = new Set());
            }
            reset();
            return O.assign(new Colors(), {
                spans: this.spans
                    .map(function (span) {
                    var e_2, _a;
                    var c = span.code;
                    var inverted = styles.has('inverse'), underline = styles.has('underline') ? 'text-decoration: underline;' : '', italic = styles.has('italic') ? 'font-style: italic;' : '', bold = brightness === Code.bright ? 'font-weight: bold;' : '';
                    var foreColor = color.defaultBrightness(brightness);
                    var styledSpan = O.assign({ css: bold + italic + underline + foreColor.css(inverted) + bgColor.css(inverted) }, clean({ bold: !!bold, color: foreColor.clean, bgColor: bgColor.clean }), span);
                    try {
                        for (var styles_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](styles), styles_1_1 = styles_1.next(); !styles_1_1.done; styles_1_1 = styles_1.next()) {
                            var k = styles_1_1.value;
                            styledSpan[k] = true;
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (styles_1_1 && !styles_1_1.done && (_a = styles_1.return)) _a.call(styles_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                    if (c.isBrightness) {
                        brightness = c.value;
                    }
                    else if (span.code.value !== undefined) {
                        if (span.code.value === Code.reset) {
                            reset();
                        }
                        else {
                            switch (span.code.type) {
                                case 'color':
                                case 'colorLight':
                                    color = new Color(false, c.subtype);
                                    break;
                                case 'bgColor':
                                case 'bgColorLight':
                                    bgColor = new Color(true, c.subtype);
                                    break;
                                case 'style':
                                    styles.add(c.subtype);
                                    break;
                                case 'unstyle':
                                    styles.delete(c.subtype);
                                    break;
                            }
                        }
                    }
                    return styledSpan;
                })
                    .filter(function (s) { return s.text.length > 0; }),
            });
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Colors.prototype, "asChromeConsoleLogArguments", {
        /*  Outputs with Chrome DevTools-compatible format     */
        get: function () {
            var spans = this.parsed.spans;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([spans.map(function (s) { return '%c' + s.text; }).join('')], spans.map(function (s) { return s.css; }));
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Colors.prototype, "browserConsoleArguments", {
        get: function () {
            return this.asChromeConsoleLogArguments;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Colors, "nice", {
        /**
         * @desc installs String prototype extensions
         * @example
         * require ('ansicolor').nice
         * console.log ('foo'.bright.red)
         */
        get: function () {
            Colors.names.forEach(function (k) {
                if (!(k in String.prototype)) {
                    O.defineProperty(String.prototype, k, {
                        get: function () {
                            // @ts-ignore
                            return Colors[k](this);
                        },
                    });
                }
            });
            return Colors;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @desc parses a string containing ANSI escape codes
     * @return {Colors} parsed representation.
     */
    Colors.parse = function (s) {
        return new Colors(s).parsed;
    };
    /**
     * @desc strips ANSI codes from a string
     * @param {string} s a string containing ANSI escape codes.
     * @return {string} clean string.
     */
    Colors.strip = function (s) {
        return s.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g, ''); // hope V8 caches the regexp
    };
    /**
     * @example
     * const spans = [...ansi.parse ('\u001b[7m\u001b[7mfoo\u001b[7mbar\u001b[27m')]
     */
    Colors.prototype[Symbol.iterator] = function () {
        return this.spans[Symbol.iterator]();
    };
    Colors.names = stringWrappingMethods.map(function (_a) {
        var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](_a, 1), k = _b[0];
        return k;
    });
    Colors.rgb = {
        black: [0, 0, 0],
        darkGray: [100, 100, 100],
        lightGray: [200, 200, 200],
        white: [255, 255, 255],
        red: [204, 0, 0],
        lightRed: [255, 51, 0],
        green: [0, 204, 0],
        lightGreen: [51, 204, 51],
        yellow: [204, 102, 0],
        lightYellow: [255, 153, 51],
        blue: [0, 0, 255],
        lightBlue: [26, 140, 255],
        magenta: [204, 0, 204],
        lightMagenta: [255, 0, 255],
        cyan: [0, 153, 255],
        lightCyan: [0, 204, 255],
    };
    return Colors;
}());
/* harmony default export */ __webpack_exports__["default"] = (Colors);
/*  ------------------------------------------------------------------------ */
assignStringWrappingAPI(Colors, function (str) { return str; });


/***/ }),

/***/ "./packages/grafana-ui/src/utils/colors.ts":
/*!*************************************************!*\
  !*** ./packages/grafana-ui/src/utils/colors.ts ***!
  \*************************************************/
/*! exports provided: PALETTE_ROWS, PALETTE_COLUMNS, DEFAULT_ANNOTATION_COLOR, OK_COLOR, ALERTING_COLOR, NO_DATA_COLOR, PENDING_COLOR, REGION_FILL_ALPHA, colors, sortedColors */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PALETTE_ROWS", function() { return PALETTE_ROWS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PALETTE_COLUMNS", function() { return PALETTE_COLUMNS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_ANNOTATION_COLOR", function() { return DEFAULT_ANNOTATION_COLOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OK_COLOR", function() { return OK_COLOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ALERTING_COLOR", function() { return ALERTING_COLOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NO_DATA_COLOR", function() { return NO_DATA_COLOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PENDING_COLOR", function() { return PENDING_COLOR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "REGION_FILL_ALPHA", function() { return REGION_FILL_ALPHA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colors", function() { return colors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortedColors", function() { return sortedColors; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/map */ "./node_modules/lodash/map.js");
/* harmony import */ var lodash_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_map__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/sortBy */ "./node_modules/lodash/sortBy.js");
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_sortBy__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_flattenDeep__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/flattenDeep */ "./node_modules/lodash/flattenDeep.js");
/* harmony import */ var lodash_flattenDeep__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_flattenDeep__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash_chunk__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash/chunk */ "./node_modules/lodash/chunk.js");
/* harmony import */ var lodash_chunk__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash_chunk__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var lodash_zip__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash/zip */ "./node_modules/lodash/zip.js");
/* harmony import */ var lodash_zip__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(lodash_zip__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_6__);







var PALETTE_ROWS = 4;
var PALETTE_COLUMNS = 14;
var DEFAULT_ANNOTATION_COLOR = 'rgba(0, 211, 255, 1)';
var OK_COLOR = 'rgba(11, 237, 50, 1)';
var ALERTING_COLOR = 'rgba(237, 46, 24, 1)';
var NO_DATA_COLOR = 'rgba(150, 150, 150, 1)';
var PENDING_COLOR = 'rgba(247, 149, 32, 1)';
var REGION_FILL_ALPHA = 0.09;
var colors = [
    '#7EB26D',
    '#EAB839',
    '#6ED0E0',
    '#EF843C',
    '#E24D42',
    '#1F78C1',
    '#BA43A9',
    '#705DA0',
    '#508642',
    '#CCA300',
    '#447EBC',
    '#C15C17',
    '#890F02',
    '#0A437C',
    '#6D1F62',
    '#584477',
    '#B7DBAB',
    '#F4D598',
    '#70DBED',
    '#F9BA8F',
    '#F29191',
    '#82B5D8',
    '#E5A8E2',
    '#AEA2E0',
    '#629E51',
    '#E5AC0E',
    '#64B0C8',
    '#E0752D',
    '#BF1B00',
    '#0A50A1',
    '#962D82',
    '#614D93',
    '#9AC48A',
    '#F2C96D',
    '#65C5DB',
    '#F9934E',
    '#EA6460',
    '#5195CE',
    '#D683CE',
    '#806EB7',
    '#3F6833',
    '#967302',
    '#2F575E',
    '#99440A',
    '#58140C',
    '#052B51',
    '#511749',
    '#3F2B5B',
    '#E0F9D7',
    '#FCEACA',
    '#CFFAFF',
    '#F9E2D2',
    '#FCE2DE',
    '#BADFF4',
    '#F9D9F9',
    '#DEDAF7',
];
function sortColorsByHue(hexColors) {
    var hslColors = lodash_map__WEBPACK_IMPORTED_MODULE_1___default()(hexColors, hexToHsl);
    var sortedHSLColors = lodash_sortBy__WEBPACK_IMPORTED_MODULE_2___default()(hslColors, ['h']);
    var chunkedHSLColors = lodash_chunk__WEBPACK_IMPORTED_MODULE_4___default()(sortedHSLColors, PALETTE_ROWS);
    var sortedChunkedHSLColors = lodash_map__WEBPACK_IMPORTED_MODULE_1___default()(chunkedHSLColors, function (chunk) {
        return lodash_sortBy__WEBPACK_IMPORTED_MODULE_2___default()(chunk, 'l');
    });
    var flattenedZippedSortedChunkedHSLColors = lodash_flattenDeep__WEBPACK_IMPORTED_MODULE_3___default()(lodash_zip__WEBPACK_IMPORTED_MODULE_5___default.a.apply(void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](sortedChunkedHSLColors)));
    return lodash_map__WEBPACK_IMPORTED_MODULE_1___default()(flattenedZippedSortedChunkedHSLColors, hslToHex);
}
function hexToHsl(color) {
    return tinycolor2__WEBPACK_IMPORTED_MODULE_6___default()(color).toHsl();
}
function hslToHex(color) {
    return tinycolor2__WEBPACK_IMPORTED_MODULE_6___default()(color).toHexString();
}
var sortedColors = sortColorsByHue(colors);


/***/ }),

/***/ "./packages/grafana-ui/src/utils/dataLinks.ts":
/*!****************************************************!*\
  !*** ./packages/grafana-ui/src/utils/dataLinks.ts ***!
  \****************************************************/
/*! exports provided: DataLinkBuiltInVars, linkModelToContextMenuItems */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLinkBuiltInVars", function() { return DataLinkBuiltInVars; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linkModelToContextMenuItems", function() { return linkModelToContextMenuItems; });
var DataLinkBuiltInVars = {
    keepTime: '__url_time_range',
    timeRangeFrom: '__from',
    timeRangeTo: '__to',
    includeVars: '__all_variables',
    seriesName: '__series.name',
    fieldName: '__field.name',
    valueTime: '__value.time',
    valueNumeric: '__value.numeric',
    valueText: '__value.text',
    valueRaw: '__value.raw',
    // name of the calculation represented by the value
    valueCalc: '__value.calc',
};
/**
 * Delays creating links until we need to open the ContextMenu
 */
var linkModelToContextMenuItems = function (links) {
    return links.getLinks().map(function (link) {
        return {
            label: link.title,
            // TODO: rename to href
            url: link.href,
            target: link.target,
            icon: "fa " + (link.target === '_self' ? 'fa-link' : 'fa-external-link'),
        };
    });
};


/***/ }),

/***/ "./packages/grafana-ui/src/utils/displayProcessor.ts":
/*!***********************************************************!*\
  !*** ./packages/grafana-ui/src/utils/displayProcessor.ts ***!
  \***********************************************************/
/*! exports provided: getDisplayProcessor, getColorFromThreshold, getDecimalsForValue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDisplayProcessor", function() { return getDisplayProcessor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorFromThreshold", function() { return getColorFromThreshold; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDecimalsForValue", function() { return getDecimalsForValue; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./valueFormats/valueFormats */ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts");
/* harmony import */ var _namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony import */ var _types_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../types/index */ "./packages/grafana-ui/src/types/index.ts");
// Libraries


// Utils


// Types

function getDisplayProcessor(options) {
    if (options && !lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isEmpty(options)) {
        var field_1 = options.config ? options.config : {};
        var formatFunc_1 = Object(_valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_2__["getValueFormat"])(field_1.unit || 'none');
        return function (value) {
            var theme = options.theme;
            var mappings = field_1.mappings, thresholds = field_1.thresholds;
            var color;
            var text = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.toString(value);
            var numeric = toNumber(value);
            var shouldFormat = true;
            if (mappings && mappings.length > 0) {
                var mappedValue = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["getMappedValue"])(mappings, value);
                if (mappedValue) {
                    text = mappedValue.text;
                    var v = toNumber(text);
                    if (!isNaN(v)) {
                        numeric = v;
                    }
                    shouldFormat = false;
                }
            }
            if (!isNaN(numeric)) {
                if (shouldFormat && !lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isBoolean(value)) {
                    var _a = getDecimalsForValue(value, field_1.decimals), decimals = _a.decimals, scaledDecimals = _a.scaledDecimals;
                    text = formatFunc_1(numeric, decimals, scaledDecimals, options.isUtc);
                    // Check if the formatted text mapped to a different value
                    if (mappings && mappings.length > 0) {
                        var mappedValue = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["getMappedValue"])(mappings, text);
                        if (mappedValue) {
                            text = mappedValue.text;
                        }
                    }
                }
                if (thresholds && thresholds.length) {
                    color = getColorFromThreshold(numeric, thresholds, theme);
                }
            }
            if (!text) {
                if (field_1 && field_1.noValue) {
                    text = field_1.noValue;
                }
                else {
                    text = ''; // No data?
                }
            }
            return { text: text, numeric: numeric, color: color };
        };
    }
    return toStringProcessor;
}
/** Will return any value as a number or NaN */
function toNumber(value) {
    if (typeof value === 'number') {
        return value;
    }
    if (value === null || value === undefined || Array.isArray(value)) {
        return NaN; // lodash calls them 0
    }
    if (typeof value === 'boolean') {
        return value ? 1 : 0;
    }
    return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.toNumber(value);
}
function toStringProcessor(value) {
    return { text: lodash__WEBPACK_IMPORTED_MODULE_0___default.a.toString(value), numeric: toNumber(value) };
}
function getColorFromThreshold(value, thresholds, theme) {
    var themeType = theme ? theme.type : _types_index__WEBPACK_IMPORTED_MODULE_4__["GrafanaThemeType"].Dark;
    if (thresholds.length === 1) {
        return Object(_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(thresholds[0].color, themeType);
    }
    var atThreshold = thresholds.filter(function (threshold) { return value === threshold.value; })[0];
    if (atThreshold) {
        return Object(_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(atThreshold.color, themeType);
    }
    var belowThreshold = thresholds.filter(function (threshold) { return value > threshold.value; });
    if (belowThreshold.length > 0) {
        var nearestThreshold = belowThreshold.sort(function (t1, t2) { return t2.value - t1.value; })[0];
        return Object(_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(nearestThreshold.color, themeType);
    }
    // Use the first threshold as the default color
    return Object(_namedColorsPalette__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(thresholds[0].color, themeType);
}
// function getSignificantDigitCount(n: number): number {
//   // remove decimal and make positive
//   n = Math.abs(parseInt(String(n).replace('.', ''), 10));
//   if (n === 0) {
//     return 0;
//   }
//
//   // kill the 0s at the end of n
//   while (n !== 0 && n % 10 === 0) {
//     n /= 10;
//   }
//
//   // get number of digits
//   return Math.floor(Math.log(n) / Math.LN10) + 1;
// }
function getDecimalsForValue(value, decimalOverride) {
    if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(decimalOverride)) {
        // It's important that scaledDecimals is null here
        return { decimals: decimalOverride, scaledDecimals: null };
    }
    var dec = -Math.floor(Math.log(value) / Math.LN10) + 1;
    var magn = Math.pow(10, -dec);
    var norm = value / magn; // norm is between 1.0 and 10.0
    var size;
    if (norm < 1.5) {
        size = 1;
    }
    else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25) {
            size = 2.5;
            ++dec;
        }
    }
    else if (norm < 7.5) {
        size = 5;
    }
    else {
        size = 10;
    }
    size *= magn;
    // reduce starting decimals if not needed
    if (value % 1 === 0) {
        dec = 0;
    }
    var decimals = Math.max(0, dec);
    var scaledDecimals = decimals - Math.floor(Math.log(size) / Math.LN10) + 2;
    return { decimals: decimals, scaledDecimals: scaledDecimals };
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/dom.ts":
/*!**********************************************!*\
  !*** ./packages/grafana-ui/src/utils/dom.ts ***!
  \**********************************************/
/*! exports provided: getPreviousCousin, getNextCharacter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPreviousCousin", function() { return getPreviousCousin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextCharacter", function() { return getNextCharacter; });
// Node.closest() polyfill
if ('Element' in window && !Element.prototype.closest) {
    Element.prototype.closest = function (s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s);
        var el = this;
        var i;
        // eslint-disable-next-line
        do {
            i = matches.length;
            // eslint-disable-next-line
            while (--i >= 0 && matches.item(i) !== el) { }
            el = el.parentElement;
        } while (i < 0 && el);
        return el;
    };
}
function getPreviousCousin(node, selector) {
    var sibling = node.parentElement.previousSibling;
    var el;
    while (sibling) {
        el = sibling.querySelector(selector);
        if (el) {
            return el;
        }
        sibling = sibling.previousSibling;
    }
    return undefined;
}
function getNextCharacter(global) {
    if (global === void 0) { global = window; }
    var selection = global.getSelection();
    if (!selection || !selection.anchorNode) {
        return null;
    }
    var range = selection.getRangeAt(0);
    var text = selection.anchorNode.textContent;
    var offset = range.startOffset;
    return text.substr(offset, 1);
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/fieldDisplay.ts":
/*!*******************************************************!*\
  !*** ./packages/grafana-ui/src/utils/fieldDisplay.ts ***!
  \*******************************************************/
/*! exports provided: VAR_SERIES_NAME, VAR_FIELD_NAME, VAR_CALC, VAR_CELL_PREFIX, DEFAULT_FIELD_DISPLAY_VALUES_LIMIT, getFieldDisplayValues, applyFieldProperties, getFieldProperties */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VAR_SERIES_NAME", function() { return VAR_SERIES_NAME; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VAR_FIELD_NAME", function() { return VAR_FIELD_NAME; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VAR_CALC", function() { return VAR_CALC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VAR_CELL_PREFIX", function() { return VAR_CELL_PREFIX; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_FIELD_DISPLAY_VALUES_LIMIT", function() { return DEFAULT_FIELD_DISPLAY_VALUES_LIMIT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldDisplayValues", function() { return getFieldDisplayValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyFieldProperties", function() { return applyFieldProperties; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldProperties", function() { return getFieldProperties; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var lodash_toNumber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/toNumber */ "./node_modules/lodash/toNumber.js");
/* harmony import */ var lodash_toNumber__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_toNumber__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_toString__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/toString */ "./node_modules/lodash/toString.js");
/* harmony import */ var lodash_toString__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_toString__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _displayProcessor__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./displayProcessor */ "./packages/grafana-ui/src/utils/displayProcessor.ts");
/* harmony import */ var _flotPairs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flotPairs */ "./packages/grafana-ui/src/utils/flotPairs.ts");






// TODO: use built in variables, same as for data links?
var VAR_SERIES_NAME = '__series.name';
var VAR_FIELD_NAME = '__field.name';
var VAR_CALC = '__calc';
var VAR_CELL_PREFIX = '__cell_'; // consistent with existing table templates
function getTitleTemplate(title, stats, data) {
    var e_1, _a;
    // If the title exists, use it as a template variable
    if (title) {
        return title;
    }
    if (!data || !data.length) {
        return 'No Data';
    }
    var fieldCount = 0;
    try {
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data[0].fields), _c = _b.next(); !_c.done; _c = _b.next()) {
            var field = _c.value;
            if (field.type === _grafana_data__WEBPACK_IMPORTED_MODULE_1__["FieldType"].number) {
                fieldCount++;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_1) throw e_1.error; }
    }
    var parts = [];
    if (stats.length > 1) {
        parts.push('${' + VAR_CALC + '}');
    }
    if (data.length > 1) {
        parts.push('${' + VAR_SERIES_NAME + '}');
    }
    if (fieldCount > 1 || !parts.length) {
        parts.push('${' + VAR_FIELD_NAME + '}');
    }
    return parts.join(' ');
}
var DEFAULT_FIELD_DISPLAY_VALUES_LIMIT = 25;
var getFieldDisplayValues = function (options) {
    var e_2, _a;
    var data = options.data, replaceVariables = options.replaceVariables, fieldOptions = options.fieldOptions;
    var defaults = fieldOptions.defaults, override = fieldOptions.override;
    var calcs = fieldOptions.calcs.length ? fieldOptions.calcs : [_grafana_data__WEBPACK_IMPORTED_MODULE_1__["ReducerID"].last];
    var values = [];
    if (data) {
        var hitLimit = false;
        var limit = fieldOptions.limit ? fieldOptions.limit : DEFAULT_FIELD_DISPLAY_VALUES_LIMIT;
        var defaultTitle = getTitleTemplate(fieldOptions.defaults.title, calcs, data);
        var scopedVars = {};
        for (var s = 0; s < data.length && !hitLimit; s++) {
            var series = data[s];
            if (!series.name) {
                series = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series, { name: series.refId ? series.refId : "Series[" + s + "]" });
            }
            scopedVars['__series'] = { text: 'Series', value: { name: series.name } };
            var timeField = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["getTimeField"])(series).timeField;
            var view = new _grafana_data__WEBPACK_IMPORTED_MODULE_1__["DataFrameView"](series);
            for (var i = 0; i < series.fields.length && !hitLimit; i++) {
                var field = series.fields[i];
                // Show all number fields
                if (field.type !== _grafana_data__WEBPACK_IMPORTED_MODULE_1__["FieldType"].number) {
                    continue;
                }
                var config = getFieldProperties(defaults, field.config || {}, override);
                var name = field.name;
                if (!name) {
                    name = "Field[" + s + "]";
                }
                scopedVars['__field'] = { text: 'Field', value: { name: name } };
                var display = Object(_displayProcessor__WEBPACK_IMPORTED_MODULE_4__["getDisplayProcessor"])({
                    config: config,
                    theme: options.theme,
                });
                var title = config.title ? config.title : defaultTitle;
                // Show all rows
                if (fieldOptions.values) {
                    var usesCellValues = title.indexOf(VAR_CELL_PREFIX) >= 0;
                    for (var j = 0; j < field.values.length; j++) {
                        // Add all the row variables
                        if (usesCellValues) {
                            for (var k = 0; k < series.fields.length; k++) {
                                var f = series.fields[k];
                                var v = f.values.get(j);
                                scopedVars[VAR_CELL_PREFIX + k] = {
                                    value: v,
                                    text: lodash_toString__WEBPACK_IMPORTED_MODULE_3___default()(v),
                                };
                            }
                        }
                        var displayValue = display(field.values.get(j));
                        displayValue.title = replaceVariables(title, scopedVars);
                        values.push({
                            name: name,
                            field: config,
                            display: displayValue,
                            view: view,
                            colIndex: i,
                            rowIndex: j,
                        });
                        if (values.length >= limit) {
                            hitLimit = true;
                            break;
                        }
                    }
                }
                else {
                    var results = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["reduceField"])({
                        field: field,
                        reducers: calcs,
                    });
                    var sparkline = undefined;
                    // Single sparkline for every reducer
                    if (options.sparkline && timeField) {
                        sparkline = Object(_flotPairs__WEBPACK_IMPORTED_MODULE_5__["getFlotPairs"])({
                            xField: timeField,
                            yField: series.fields[i],
                        });
                    }
                    try {
                        for (var calcs_1 = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](calcs)), calcs_1_1 = calcs_1.next(); !calcs_1_1.done; calcs_1_1 = calcs_1.next()) {
                            var calc = calcs_1_1.value;
                            scopedVars[VAR_CALC] = { value: calc, text: calc };
                            var displayValue = display(results[calc]);
                            displayValue.title = replaceVariables(title, scopedVars);
                            values.push({
                                name: calc,
                                field: config,
                                display: displayValue,
                                sparkline: sparkline,
                                view: view,
                                colIndex: i,
                            });
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (calcs_1_1 && !calcs_1_1.done && (_a = calcs_1.return)) _a.call(calcs_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
            }
        }
    }
    if (values.length === 0) {
        values.push({
            name: 'No data',
            field: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaults),
            display: {
                numeric: 0,
                text: 'No data',
            },
        });
    }
    else if (values.length === 1 && !fieldOptions.defaults.title) {
        // Don't show title for single item
        values[0].display.title = undefined;
    }
    return values;
};
var numericFieldProps = {
    decimals: true,
    min: true,
    max: true,
};
/**
 * Returns a version of the field with the overries applied.  Any property with
 * value: null | undefined | empty string are skipped.
 *
 * For numeric values, only valid numbers will be applied
 * for units, 'none' will be skipped
 */
function applyFieldProperties(field, props) {
    var e_3, _a;
    if (!props) {
        return field;
    }
    var keys = Object.keys(props);
    if (!keys.length) {
        return field;
    }
    var copy = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field); // make a copy that we will manipulate directly
    try {
        for (var keys_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
            var key = keys_1_1.value;
            var val = props[key];
            if (val === null || val === undefined) {
                continue;
            }
            if (numericFieldProps[key]) {
                var num = lodash_toNumber__WEBPACK_IMPORTED_MODULE_2___default()(val);
                if (!isNaN(num)) {
                    copy[key] = num;
                }
            }
            else if (val) {
                // skips empty string
                if (key === 'unit' && val === 'none') {
                    continue;
                }
                copy[key] = val;
            }
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
        }
        finally { if (e_3) throw e_3.error; }
    }
    return copy;
}
function getFieldProperties() {
    var props = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        props[_i] = arguments[_i];
    }
    var field = props[0];
    for (var i = 1; i < props.length; i++) {
        field = applyFieldProperties(field, props[i]);
    }
    // First value is always -Infinity
    if (field.thresholds && field.thresholds.length) {
        field.thresholds[0].value = -Infinity;
    }
    // Verify that max > min
    if (field.hasOwnProperty('min') && field.hasOwnProperty('max') && field.min > field.max) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, field, { min: field.max, max: field.min });
    }
    return field;
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/flotPairs.ts":
/*!****************************************************!*\
  !*** ./packages/grafana-ui/src/utils/flotPairs.ts ***!
  \****************************************************/
/*! exports provided: getFlotPairs, getFlotPairsConstant */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFlotPairs", function() { return getFlotPairs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFlotPairsConstant", function() { return getFlotPairsConstant; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
// Types

function getFlotPairs(_a) {
    var xField = _a.xField, yField = _a.yField, nullValueMode = _a.nullValueMode;
    var vX = xField.values;
    var vY = yField.values;
    var length = vX.length;
    if (vY.length !== length) {
        throw new Error('Unexpected field length');
    }
    var ignoreNulls = nullValueMode === _grafana_data__WEBPACK_IMPORTED_MODULE_0__["NullValueMode"].Ignore;
    var nullAsZero = nullValueMode === _grafana_data__WEBPACK_IMPORTED_MODULE_0__["NullValueMode"].AsZero;
    var pairs = [];
    for (var i = 0; i < length; i++) {
        var x = vX.get(i);
        var y = vY.get(i);
        if (y === null) {
            if (ignoreNulls) {
                continue;
            }
            if (nullAsZero) {
                y = 0;
            }
        }
        // X must be a value
        if (x === null) {
            continue;
        }
        pairs.push([x, y]);
    }
    return pairs;
}
/**
 * Returns a constant series based on the first value from the provide series.
 * @param seriesData Series
 * @param range Start and end time for the constant series
 */
function getFlotPairsConstant(seriesData, range) {
    if (!range.from || !range.to || !seriesData || seriesData.length === 0) {
        return [];
    }
    var from = range.from.valueOf();
    var to = range.to.valueOf();
    var value = seriesData[0][1];
    return [[from, value], [to, value]];
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/index.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/utils/index.ts ***!
  \************************************************/
/*! exports provided: toFixed, toFixedScaled, toFixedUnit, scaledUnits, locale, simpleCountUnit, getValueFormat, getValueFormatterIndex, getValueFormats, PALETTE_ROWS, PALETTE_COLUMNS, DEFAULT_ANNOTATION_COLOR, OK_COLOR, ALERTING_COLOR, NO_DATA_COLOR, PENDING_COLOR, REGION_FILL_ALPHA, colors, sortedColors, getColorDefinitionByName, getColorDefinition, getColorName, getColorByName, getColorFromHexRgbOrName, getColorForTheme, getNamedColorPalette, getDisplayProcessor, getColorFromThreshold, getDecimalsForValue, VAR_SERIES_NAME, VAR_FIELD_NAME, VAR_CALC, VAR_CELL_PREFIX, DEFAULT_FIELD_DISPLAY_VALUES_LIMIT, getFieldDisplayValues, applyFieldProperties, getFieldProperties, EventsWithValidation, validate, hasValidationEvent, getFlotPairs, getFlotPairsConstant, SCHEMA, makeFragment, makeValue, DataLinkBuiltInVars, linkModelToContextMenuItems, ansicolor, DOMUtil */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./valueFormats/valueFormats */ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFixed", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixed"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFixedScaled", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedScaled"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "toFixedUnit", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "scaledUnits", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["scaledUnits"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "locale", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["locale"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "simpleCountUnit", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getValueFormat", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["getValueFormat"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getValueFormatterIndex", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["getValueFormatterIndex"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getValueFormats", function() { return _valueFormats_valueFormats__WEBPACK_IMPORTED_MODULE_0__["getValueFormats"]; });

/* harmony import */ var _colors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./colors */ "./packages/grafana-ui/src/utils/colors.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PALETTE_ROWS", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["PALETTE_ROWS"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PALETTE_COLUMNS", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["PALETTE_COLUMNS"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_ANNOTATION_COLOR", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["DEFAULT_ANNOTATION_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OK_COLOR", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["OK_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ALERTING_COLOR", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["ALERTING_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NO_DATA_COLOR", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["NO_DATA_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PENDING_COLOR", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["PENDING_COLOR"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "REGION_FILL_ALPHA", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["REGION_FILL_ALPHA"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "colors", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["colors"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sortedColors", function() { return _colors__WEBPACK_IMPORTED_MODULE_1__["sortedColors"]; });

/* harmony import */ var _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./namedColorsPalette */ "./packages/grafana-ui/src/utils/namedColorsPalette.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorDefinitionByName", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorDefinitionByName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorDefinition", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorDefinition"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorName", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorByName", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorByName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorFromHexRgbOrName", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorFromHexRgbOrName"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorForTheme", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getColorForTheme"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getNamedColorPalette", function() { return _namedColorsPalette__WEBPACK_IMPORTED_MODULE_2__["getNamedColorPalette"]; });

/* harmony import */ var _displayProcessor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./displayProcessor */ "./packages/grafana-ui/src/utils/displayProcessor.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDisplayProcessor", function() { return _displayProcessor__WEBPACK_IMPORTED_MODULE_3__["getDisplayProcessor"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getColorFromThreshold", function() { return _displayProcessor__WEBPACK_IMPORTED_MODULE_3__["getColorFromThreshold"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getDecimalsForValue", function() { return _displayProcessor__WEBPACK_IMPORTED_MODULE_3__["getDecimalsForValue"]; });

/* harmony import */ var _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fieldDisplay */ "./packages/grafana-ui/src/utils/fieldDisplay.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_SERIES_NAME", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["VAR_SERIES_NAME"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_FIELD_NAME", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["VAR_FIELD_NAME"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_CALC", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["VAR_CALC"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VAR_CELL_PREFIX", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["VAR_CELL_PREFIX"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_FIELD_DISPLAY_VALUES_LIMIT", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["DEFAULT_FIELD_DISPLAY_VALUES_LIMIT"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFieldDisplayValues", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["getFieldDisplayValues"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "applyFieldProperties", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["applyFieldProperties"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFieldProperties", function() { return _fieldDisplay__WEBPACK_IMPORTED_MODULE_4__["getFieldProperties"]; });

/* harmony import */ var _validate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./validate */ "./packages/grafana-ui/src/utils/validate.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventsWithValidation", function() { return _validate__WEBPACK_IMPORTED_MODULE_5__["EventsWithValidation"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "validate", function() { return _validate__WEBPACK_IMPORTED_MODULE_5__["validate"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasValidationEvent", function() { return _validate__WEBPACK_IMPORTED_MODULE_5__["hasValidationEvent"]; });

/* harmony import */ var _flotPairs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flotPairs */ "./packages/grafana-ui/src/utils/flotPairs.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFlotPairs", function() { return _flotPairs__WEBPACK_IMPORTED_MODULE_6__["getFlotPairs"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getFlotPairsConstant", function() { return _flotPairs__WEBPACK_IMPORTED_MODULE_6__["getFlotPairsConstant"]; });

/* harmony import */ var _slate__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./slate */ "./packages/grafana-ui/src/utils/slate.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SCHEMA", function() { return _slate__WEBPACK_IMPORTED_MODULE_7__["SCHEMA"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "makeFragment", function() { return _slate__WEBPACK_IMPORTED_MODULE_7__["makeFragment"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "makeValue", function() { return _slate__WEBPACK_IMPORTED_MODULE_7__["makeValue"]; });

/* harmony import */ var _dataLinks__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./dataLinks */ "./packages/grafana-ui/src/utils/dataLinks.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataLinkBuiltInVars", function() { return _dataLinks__WEBPACK_IMPORTED_MODULE_8__["DataLinkBuiltInVars"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "linkModelToContextMenuItems", function() { return _dataLinks__WEBPACK_IMPORTED_MODULE_8__["linkModelToContextMenuItems"]; });

/* harmony import */ var _ansicolor__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./ansicolor */ "./packages/grafana-ui/src/utils/ansicolor.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ansicolor", function() { return _ansicolor__WEBPACK_IMPORTED_MODULE_9__["default"]; });

/* harmony import */ var _dom__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./dom */ "./packages/grafana-ui/src/utils/dom.ts");
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "DOMUtil", function() { return _dom__WEBPACK_IMPORTED_MODULE_10__; });










// Export with a namespace
 // includes Element.closest polyfil



/***/ }),

/***/ "./packages/grafana-ui/src/utils/namedColorsPalette.ts":
/*!*************************************************************!*\
  !*** ./packages/grafana-ui/src/utils/namedColorsPalette.ts ***!
  \*************************************************************/
/*! exports provided: getColorDefinitionByName, getColorDefinition, getColorName, getColorByName, getColorFromHexRgbOrName, getColorForTheme, getNamedColorPalette */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorDefinitionByName", function() { return getColorDefinitionByName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorDefinition", function() { return getColorDefinition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorName", function() { return getColorName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorByName", function() { return getColorByName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorFromHexRgbOrName", function() { return getColorFromHexRgbOrName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorForTheme", function() { return getColorForTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNamedColorPalette", function() { return getNamedColorPalette; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_flatten__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/flatten */ "./node_modules/lodash/flatten.js");
/* harmony import */ var lodash_flatten__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_flatten__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _types_theme__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/theme */ "./packages/grafana-ui/src/types/theme.ts");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_3__);




var colorsPaletteInstance;
var buildColorDefinition = function (hue, name, _a, isPrimary) {
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](_a, 2), light = _b[0], dark = _b[1];
    return ({
        hue: hue,
        name: name,
        variants: {
            light: light,
            dark: dark,
        },
        isPrimary: !!isPrimary,
    });
};
var getColorDefinitionByName = function (name) {
    return lodash_flatten__WEBPACK_IMPORTED_MODULE_1___default()(Array.from(getNamedColorPalette().values())).filter(function (definition) { return definition.name === name; })[0];
};
var getColorDefinition = function (hex, theme) {
    return lodash_flatten__WEBPACK_IMPORTED_MODULE_1___default()(Array.from(getNamedColorPalette().values())).filter(function (definition) { return definition.variants[theme] === hex; })[0];
};
var isHex = function (color) {
    var hexRegex = /^((0x){0,1}|#{0,1})([0-9A-F]{8}|[0-9A-F]{6}|[0-9A-F]{3})$/gi;
    return hexRegex.test(color);
};
var getColorName = function (color, theme) {
    if (!color) {
        return undefined;
    }
    if (color.indexOf('rgb') > -1) {
        return undefined;
    }
    if (isHex(color)) {
        var definition = getColorDefinition(color, theme || _types_theme__WEBPACK_IMPORTED_MODULE_2__["GrafanaThemeType"].Dark);
        return definition ? definition.name : undefined;
    }
    return color;
};
var getColorByName = function (colorName) {
    var definition = lodash_flatten__WEBPACK_IMPORTED_MODULE_1___default()(Array.from(getNamedColorPalette().values())).filter(function (definition) { return definition.name === colorName; });
    return definition.length > 0 ? definition[0] : undefined;
};
var getColorFromHexRgbOrName = function (color, theme) {
    if (color.indexOf('rgb') > -1 || isHex(color)) {
        return color;
    }
    var colorDefinition = getColorByName(color);
    if (!colorDefinition) {
        return new tinycolor2__WEBPACK_IMPORTED_MODULE_3___default.a(color).toHexString();
    }
    return theme ? colorDefinition.variants[theme] : colorDefinition.variants.dark;
};
var getColorForTheme = function (color, theme) {
    return theme ? color.variants[theme] : color.variants.dark;
};
var buildNamedColorsPalette = function () {
    var palette = new Map();
    var BasicGreen = buildColorDefinition('green', 'green', ['#56A64B', '#73BF69'], true);
    var DarkGreen = buildColorDefinition('green', 'dark-green', ['#19730E', '#37872D']);
    var SemiDarkGreen = buildColorDefinition('green', 'semi-dark-green', ['#37872D', '#56A64B']);
    var LightGreen = buildColorDefinition('green', 'light-green', ['#73BF69', '#96D98D']);
    var SuperLightGreen = buildColorDefinition('green', 'super-light-green', ['#96D98D', '#C8F2C2']);
    var BasicYellow = buildColorDefinition('yellow', 'yellow', ['#F2CC0C', '#FADE2A'], true);
    var DarkYellow = buildColorDefinition('yellow', 'dark-yellow', ['#CC9D00', '#E0B400']);
    var SemiDarkYellow = buildColorDefinition('yellow', 'semi-dark-yellow', ['#E0B400', '#F2CC0C']);
    var LightYellow = buildColorDefinition('yellow', 'light-yellow', ['#FADE2A', '#FFEE52']);
    var SuperLightYellow = buildColorDefinition('yellow', 'super-light-yellow', ['#FFEE52', '#FFF899']);
    var BasicRed = buildColorDefinition('red', 'red', ['#E02F44', '#F2495C'], true);
    var DarkRed = buildColorDefinition('red', 'dark-red', ['#AD0317', '#C4162A']);
    var SemiDarkRed = buildColorDefinition('red', 'semi-dark-red', ['#C4162A', '#E02F44']);
    var LightRed = buildColorDefinition('red', 'light-red', ['#F2495C', '#FF7383']);
    var SuperLightRed = buildColorDefinition('red', 'super-light-red', ['#FF7383', '#FFA6B0']);
    var BasicBlue = buildColorDefinition('blue', 'blue', ['#3274D9', '#5794F2'], true);
    var DarkBlue = buildColorDefinition('blue', 'dark-blue', ['#1250B0', '#1F60C4']);
    var SemiDarkBlue = buildColorDefinition('blue', 'semi-dark-blue', ['#1F60C4', '#3274D9']);
    var LightBlue = buildColorDefinition('blue', 'light-blue', ['#5794F2', '#8AB8FF']);
    var SuperLightBlue = buildColorDefinition('blue', 'super-light-blue', ['#8AB8FF', '#C0D8FF']);
    var BasicOrange = buildColorDefinition('orange', 'orange', ['#FF780A', '#FF9830'], true);
    var DarkOrange = buildColorDefinition('orange', 'dark-orange', ['#E55400', '#FA6400']);
    var SemiDarkOrange = buildColorDefinition('orange', 'semi-dark-orange', ['#FA6400', '#FF780A']);
    var LightOrange = buildColorDefinition('orange', 'light-orange', ['#FF9830', '#FFB357']);
    var SuperLightOrange = buildColorDefinition('orange', 'super-light-orange', ['#FFB357', '#FFCB7D']);
    var BasicPurple = buildColorDefinition('purple', 'purple', ['#A352CC', '#B877D9'], true);
    var DarkPurple = buildColorDefinition('purple', 'dark-purple', ['#7C2EA3', '#8F3BB8']);
    var SemiDarkPurple = buildColorDefinition('purple', 'semi-dark-purple', ['#8F3BB8', '#A352CC']);
    var LightPurple = buildColorDefinition('purple', 'light-purple', ['#B877D9', '#CA95E5']);
    var SuperLightPurple = buildColorDefinition('purple', 'super-light-purple', ['#CA95E5', '#DEB6F2']);
    var greens = [BasicGreen, DarkGreen, SemiDarkGreen, LightGreen, SuperLightGreen];
    var yellows = [BasicYellow, DarkYellow, SemiDarkYellow, LightYellow, SuperLightYellow];
    var reds = [BasicRed, DarkRed, SemiDarkRed, LightRed, SuperLightRed];
    var blues = [BasicBlue, DarkBlue, SemiDarkBlue, LightBlue, SuperLightBlue];
    var oranges = [BasicOrange, DarkOrange, SemiDarkOrange, LightOrange, SuperLightOrange];
    var purples = [BasicPurple, DarkPurple, SemiDarkPurple, LightPurple, SuperLightPurple];
    palette.set('green', greens);
    palette.set('yellow', yellows);
    palette.set('red', reds);
    palette.set('blue', blues);
    palette.set('orange', oranges);
    palette.set('purple', purples);
    return palette;
};
var getNamedColorPalette = function () {
    if (colorsPaletteInstance) {
        return colorsPaletteInstance;
    }
    colorsPaletteInstance = buildNamedColorsPalette();
    return colorsPaletteInstance;
};


/***/ }),

/***/ "./packages/grafana-ui/src/utils/slate.ts":
/*!************************************************!*\
  !*** ./packages/grafana-ui/src/utils/slate.ts ***!
  \************************************************/
/*! exports provided: SCHEMA, makeFragment, makeValue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SCHEMA", function() { return SCHEMA; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeFragment", function() { return makeFragment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeValue", function() { return makeValue; });
/* harmony import */ var slate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! slate */ "./node_modules/slate/lib/slate.es.js");

var SCHEMA = {
    document: {
        nodes: [
            {
                match: [{ type: 'paragraph' }, { type: 'code_block' }, { type: 'code_line' }],
            },
        ],
    },
    inlines: {},
};
var makeFragment = function (text, syntax) {
    var lines = text.split('\n').map(function (line) {
        return slate__WEBPACK_IMPORTED_MODULE_0__["Block"].create({
            type: 'code_line',
            nodes: [slate__WEBPACK_IMPORTED_MODULE_0__["Text"].create(line)],
        });
    });
    var block = slate__WEBPACK_IMPORTED_MODULE_0__["Block"].create({
        data: {
            syntax: syntax,
        },
        type: 'code_block',
        nodes: lines,
    });
    return slate__WEBPACK_IMPORTED_MODULE_0__["Document"].create({
        nodes: [block],
    });
};
var makeValue = function (text, syntax) {
    var fragment = makeFragment(text, syntax);
    return slate__WEBPACK_IMPORTED_MODULE_0__["Value"].create({
        document: fragment,
    });
};


/***/ }),

/***/ "./packages/grafana-ui/src/utils/validate.ts":
/*!***************************************************!*\
  !*** ./packages/grafana-ui/src/utils/validate.ts ***!
  \***************************************************/
/*! exports provided: EventsWithValidation, validate, hasValidationEvent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventsWithValidation", function() { return EventsWithValidation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validate", function() { return validate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasValidationEvent", function() { return hasValidationEvent; });
var EventsWithValidation;
(function (EventsWithValidation) {
    EventsWithValidation["onBlur"] = "onBlur";
    EventsWithValidation["onFocus"] = "onFocus";
    EventsWithValidation["onChange"] = "onChange";
})(EventsWithValidation || (EventsWithValidation = {}));
var validate = function (value, validationRules) {
    var errors = validationRules.reduce(function (acc, currRule) {
        if (!currRule.rule(value)) {
            return acc.concat(currRule.errorMessage);
        }
        return acc;
    }, []);
    return errors.length > 0 ? errors : null;
};
var hasValidationEvent = function (event, validationEvents) {
    return validationEvents && validationEvents[event];
};


/***/ }),

/***/ "./packages/grafana-ui/src/utils/valueFormats/arithmeticFormatters.ts":
/*!****************************************************************************!*\
  !*** ./packages/grafana-ui/src/utils/valueFormats/arithmeticFormatters.ts ***!
  \****************************************************************************/
/*! exports provided: toPercent, toPercentUnit, toHex0x, toHex, sci */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toPercent", function() { return toPercent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toPercentUnit", function() { return toPercentUnit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toHex0x", function() { return toHex0x; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toHex", function() { return toHex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sci", function() { return sci; });
/* harmony import */ var _valueFormats__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./valueFormats */ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts");

function toPercent(size, decimals) {
    if (size === null) {
        return '';
    }
    return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixed"])(size, decimals) + '%';
}
function toPercentUnit(size, decimals) {
    if (size === null) {
        return '';
    }
    return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixed"])(100 * size, decimals) + '%';
}
function toHex0x(value, decimals) {
    if (value == null) {
        return '';
    }
    var hexString = toHex(value, decimals);
    if (hexString.substring(0, 1) === '-') {
        return '-0x' + hexString.substring(1);
    }
    return '0x' + hexString;
}
function toHex(value, decimals) {
    if (value == null) {
        return '';
    }
    return parseFloat(Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixed"])(value, decimals))
        .toString(16)
        .toUpperCase();
}
function sci(value, decimals) {
    if (value == null) {
        return '';
    }
    return value.toExponential(decimals);
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/valueFormats/categories.ts":
/*!******************************************************************!*\
  !*** ./packages/grafana-ui/src/utils/valueFormats/categories.ts ***!
  \******************************************************************/
/*! exports provided: getCategories */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCategories", function() { return getCategories; });
/* harmony import */ var _valueFormats__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./valueFormats */ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts");
/* harmony import */ var _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dateTimeFormatters */ "./packages/grafana-ui/src/utils/valueFormats/dateTimeFormatters.ts");
/* harmony import */ var _arithmeticFormatters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./arithmeticFormatters */ "./packages/grafana-ui/src/utils/valueFormats/arithmeticFormatters.ts");
/* harmony import */ var _symbolFormatters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./symbolFormatters */ "./packages/grafana-ui/src/utils/valueFormats/symbolFormatters.ts");




var getCategories = function () { return [
    {
        name: 'Misc',
        formats: [
            { name: 'none', id: 'none', fn: _valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixed"] },
            {
                name: 'short',
                id: 'short',
                fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["scaledUnits"])(1000, ['', ' K', ' Mil', ' Bil', ' Tri', ' Quadr', ' Quint', ' Sext', ' Sept']),
            },
            { name: 'percent (0-100)', id: 'percent', fn: _arithmeticFormatters__WEBPACK_IMPORTED_MODULE_2__["toPercent"] },
            { name: 'percent (0.0-1.0)', id: 'percentunit', fn: _arithmeticFormatters__WEBPACK_IMPORTED_MODULE_2__["toPercentUnit"] },
            { name: 'Humidity (%H)', id: 'humidity', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('%H') },
            { name: 'decibel', id: 'dB', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('dB') },
            { name: 'hexadecimal (0x)', id: 'hex0x', fn: _arithmeticFormatters__WEBPACK_IMPORTED_MODULE_2__["toHex0x"] },
            { name: 'hexadecimal', id: 'hex', fn: _arithmeticFormatters__WEBPACK_IMPORTED_MODULE_2__["toHex"] },
            { name: 'scientific notation', id: 'sci', fn: _arithmeticFormatters__WEBPACK_IMPORTED_MODULE_2__["sci"] },
            { name: 'locale format', id: 'locale', fn: _valueFormats__WEBPACK_IMPORTED_MODULE_0__["locale"] },
        ],
    },
    {
        name: 'Acceleration',
        formats: [
            { name: 'Meters/sec²', id: 'accMS2', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('m/sec²') },
            { name: 'Feet/sec²', id: 'accFS2', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('f/sec²') },
            { name: 'G unit', id: 'accG', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('g') },
        ],
    },
    {
        name: 'Angle',
        formats: [
            { name: 'Degrees (°)', id: 'degree', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('°') },
            { name: 'Radians', id: 'radian', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('rad') },
            { name: 'Gradian', id: 'grad', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('grad') },
            { name: 'Arc Minutes', id: 'arcmin', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('arcmin') },
            { name: 'Arc Seconds', id: 'arcsec', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('arcsec') },
        ],
    },
    {
        name: 'Area',
        formats: [
            { name: 'Square Meters (m²)', id: 'areaM2', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('m²') },
            { name: 'Square Feet (ft²)', id: 'areaF2', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('ft²') },
            { name: 'Square Miles (mi²)', id: 'areaMI2', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mi²') },
        ],
    },
    {
        name: 'Computation',
        formats: [
            { name: 'FLOP/s', id: 'flops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s') },
            { name: 'MFLOP/s', id: 'mflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 2) },
            { name: 'GFLOP/s', id: 'gflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 3) },
            { name: 'TFLOP/s', id: 'tflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 4) },
            { name: 'PFLOP/s', id: 'pflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 5) },
            { name: 'EFLOP/s', id: 'eflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 6) },
            { name: 'ZFLOP/s', id: 'zflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 7) },
            { name: 'YFLOP/s', id: 'yflops', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('FLOP/s', 8) },
        ],
    },
    {
        name: 'Concentration',
        formats: [
            { name: 'parts-per-million (ppm)', id: 'ppm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('ppm') },
            { name: 'parts-per-billion (ppb)', id: 'conppb', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('ppb') },
            { name: 'nanogram per cubic meter (ng/m³)', id: 'conngm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('ng/m³') },
            { name: 'nanogram per normal cubic meter (ng/Nm³)', id: 'conngNm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('ng/Nm³') },
            { name: 'microgram per cubic meter (μg/m³)', id: 'conμgm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('μg/m³') },
            { name: 'microgram per normal cubic meter (μg/Nm³)', id: 'conμgNm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('μg/Nm³') },
            { name: 'milligram per cubic meter (mg/m³)', id: 'conmgm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mg/m³') },
            { name: 'milligram per normal cubic meter (mg/Nm³)', id: 'conmgNm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mg/Nm³') },
            { name: 'gram per cubic meter (g/m³)', id: 'congm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('g/m³') },
            { name: 'gram per normal cubic meter (g/Nm³)', id: 'congNm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('g/Nm³') },
            { name: 'milligrams per decilitre (mg/dL)', id: 'conmgdL', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mg/dL') },
            { name: 'millimoles per litre (mmol/L)', id: 'conmmolL', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mmol/L') },
        ],
    },
    {
        name: 'Currency',
        formats: [
            { name: 'Dollars ($)', id: 'currencyUSD', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('$') },
            { name: 'Pounds (£)', id: 'currencyGBP', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('£') },
            { name: 'Euro (€)', id: 'currencyEUR', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('€') },
            { name: 'Yen (¥)', id: 'currencyJPY', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('¥') },
            { name: 'Rubles (₽)', id: 'currencyRUB', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('₽') },
            { name: 'Hryvnias (₴)', id: 'currencyUAH', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('₴') },
            { name: 'Real (R$)', id: 'currencyBRL', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('R$') },
            { name: 'Danish Krone (kr)', id: 'currencyDKK', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('kr') },
            { name: 'Icelandic Króna (kr)', id: 'currencyISK', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('kr') },
            { name: 'Norwegian Krone (kr)', id: 'currencyNOK', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('kr') },
            { name: 'Swedish Krona (kr)', id: 'currencySEK', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('kr') },
            { name: 'Czech koruna (czk)', id: 'currencyCZK', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('czk') },
            { name: 'Swiss franc (CHF)', id: 'currencyCHF', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('CHF') },
            { name: 'Polish Złoty (PLN)', id: 'currencyPLN', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('PLN') },
            { name: 'Bitcoin (฿)', id: 'currencyBTC', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('฿') },
            { name: 'South African Rand (R)', id: 'currencyZAR', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["currency"])('R') },
        ],
    },
    {
        name: 'Data (IEC)',
        formats: [
            { name: 'bits', id: 'bits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('b') },
            { name: 'bytes', id: 'bytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('B') },
            { name: 'kibibytes', id: 'kbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('B', 1) },
            { name: 'mebibytes', id: 'mbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('B', 2) },
            { name: 'gibibytes', id: 'gbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('B', 3) },
            { name: 'tebibytes', id: 'tbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('B', 4) },
            { name: 'pebibytes', id: 'pbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["binarySIPrefix"])('B', 5) },
        ],
    },
    {
        name: 'Data (Metric)',
        formats: [
            { name: 'bits', id: 'decbits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('b') },
            { name: 'bytes', id: 'decbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('B') },
            { name: 'kilobytes', id: 'deckbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('B', 1) },
            { name: 'megabytes', id: 'decmbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('B', 2) },
            { name: 'gigabytes', id: 'decgbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('B', 3) },
            { name: 'terabytes', id: 'dectbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('B', 4) },
            { name: 'petabytes', id: 'decpbytes', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('B', 5) },
        ],
    },
    {
        name: 'Data Rate',
        formats: [
            { name: 'packets/sec', id: 'pps', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('pps') },
            { name: 'bits/sec', id: 'bps', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bps') },
            { name: 'bytes/sec', id: 'Bps', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bs') },
            { name: 'kilobytes/sec', id: 'KBs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bs', 1) },
            { name: 'kilobits/sec', id: 'Kbits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bps', 1) },
            { name: 'megabytes/sec', id: 'MBs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bs', 2) },
            { name: 'megabits/sec', id: 'Mbits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bps', 2) },
            { name: 'gigabytes/sec', id: 'GBs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bs', 3) },
            { name: 'gigabits/sec', id: 'Gbits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bps', 3) },
            { name: 'terabytes/sec', id: 'TBs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bs', 4) },
            { name: 'terabits/sec', id: 'Tbits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bps', 4) },
            { name: 'petabytes/sec', id: 'PBs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bs', 5) },
            { name: 'petabits/sec', id: 'Pbits', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bps', 5) },
        ],
    },
    {
        name: 'Date & Time',
        formats: [
            { name: 'YYYY-MM-DD HH:mm:ss', id: 'dateTimeAsIso', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["dateTimeAsIso"] },
            { name: 'DD/MM/YYYY h:mm:ss a', id: 'dateTimeAsUS', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["dateTimeAsUS"] },
            { name: 'From Now', id: 'dateTimeFromNow', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["dateTimeFromNow"] },
        ],
    },
    {
        name: 'Energy',
        formats: [
            { name: 'Watt (W)', id: 'watt', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('W') },
            { name: 'Kilowatt (kW)', id: 'kwatt', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('W', 1) },
            { name: 'Milliwatt (mW)', id: 'mwatt', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('W', -1) },
            { name: 'Watt per square meter (W/m²)', id: 'Wm2', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('W/m²') },
            { name: 'Volt-ampere (VA)', id: 'voltamp', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('VA') },
            { name: 'Kilovolt-ampere (kVA)', id: 'kvoltamp', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('VA', 1) },
            { name: 'Volt-ampere reactive (var)', id: 'voltampreact', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('var') },
            { name: 'Kilovolt-ampere reactive (kvar)', id: 'kvoltampreact', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('var', 1) },
            { name: 'Watt-hour (Wh)', id: 'watth', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Wh') },
            { name: 'Kilowatt-hour (kWh)', id: 'kwatth', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Wh', 1) },
            { name: 'Kilowatt-min (kWm)', id: 'kwattm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('W/Min', 1) },
            { name: 'Ampere-hour (Ah)', id: 'amph', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Ah') },
            { name: 'Joule (J)', id: 'joule', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('J') },
            { name: 'Electron volt (eV)', id: 'ev', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('eV') },
            { name: 'Ampere (A)', id: 'amp', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('A') },
            { name: 'Kiloampere (kA)', id: 'kamp', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('A', 1) },
            { name: 'Milliampere (mA)', id: 'mamp', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('A', -1) },
            { name: 'Volt (V)', id: 'volt', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('V') },
            { name: 'Kilovolt (kV)', id: 'kvolt', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('V', 1) },
            { name: 'Millivolt (mV)', id: 'mvolt', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('V', -1) },
            { name: 'Decibel-milliwatt (dBm)', id: 'dBm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('dBm') },
            { name: 'Ohm (Ω)', id: 'ohm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Ω') },
            { name: 'Lumens (Lm)', id: 'lumens', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Lm') },
        ],
    },
    {
        name: 'Flow',
        formats: [
            { name: 'Gallons/min (gpm)', id: 'flowgpm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('gpm') },
            { name: 'Cubic meters/sec (cms)', id: 'flowcms', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('cms') },
            { name: 'Cubic feet/sec (cfs)', id: 'flowcfs', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('cfs') },
            { name: 'Cubic feet/min (cfm)', id: 'flowcfm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('cfm') },
            { name: 'Litre/hour', id: 'litreh', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('l/h') },
            { name: 'Litre/min (l/min)', id: 'flowlpm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('l/min') },
            { name: 'milliLitre/min (mL/min)', id: 'flowmlpm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mL/min') },
            { name: 'Lux (lx)', id: 'lux', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('lux') },
        ],
    },
    {
        name: 'Force',
        formats: [
            { name: 'Newton-meters (Nm)', id: 'forceNm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Nm') },
            { name: 'Kilonewton-meters (kNm)', id: 'forcekNm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Nm', 1) },
            { name: 'Newtons (N)', id: 'forceN', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('N') },
            { name: 'Kilonewtons (kN)', id: 'forcekN', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('N', 1) },
        ],
    },
    {
        name: 'Hash Rate',
        formats: [
            { name: 'hashes/sec', id: 'Hs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s') },
            { name: 'kilohashes/sec', id: 'KHs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s', 1) },
            { name: 'megahashes/sec', id: 'MHs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s', 2) },
            { name: 'gigahashes/sec', id: 'GHs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s', 3) },
            { name: 'terahashes/sec', id: 'THs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s', 4) },
            { name: 'petahashes/sec', id: 'PHs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s', 5) },
            { name: 'exahashes/sec', id: 'EHs', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('H/s', 6) },
        ],
    },
    {
        name: 'Mass',
        formats: [
            { name: 'milligram (mg)', id: 'massmg', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('g', -1) },
            { name: 'gram (g)', id: 'massg', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('g') },
            { name: 'kilogram (kg)', id: 'masskg', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('g', 1) },
            { name: 'metric ton (t)', id: 'masst', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('t') },
        ],
    },
    {
        name: 'length',
        formats: [
            { name: 'millimetre (mm)', id: 'lengthmm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('m', -1) },
            { name: 'feet (ft)', id: 'lengthft', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('ft') },
            { name: 'meter (m)', id: 'lengthm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('m') },
            { name: 'kilometer (km)', id: 'lengthkm', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('m', 1) },
            { name: 'mile (mi)', id: 'lengthmi', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mi') },
        ],
    },
    {
        name: 'Pressure',
        formats: [
            { name: 'Millibars', id: 'pressurembar', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bar', -1) },
            { name: 'Bars', id: 'pressurebar', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bar') },
            { name: 'Kilobars', id: 'pressurekbar', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('bar', 1) },
            { name: 'Hectopascals', id: 'pressurehpa', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('hPa') },
            { name: 'Kilopascals', id: 'pressurekpa', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('kPa') },
            { name: 'Inches of mercury', id: 'pressurehg', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('"Hg') },
            { name: 'PSI', id: 'pressurepsi', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["scaledUnits"])(1000, ['psi', 'ksi', 'Mpsi']) },
        ],
    },
    {
        name: 'Radiation',
        formats: [
            { name: 'Becquerel (Bq)', id: 'radbq', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Bq') },
            { name: 'curie (Ci)', id: 'radci', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Ci') },
            { name: 'Gray (Gy)', id: 'radgy', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Gy') },
            { name: 'rad', id: 'radrad', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('rad') },
            { name: 'Sievert (Sv)', id: 'radsv', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Sv') },
            { name: 'rem', id: 'radrem', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('rem') },
            { name: 'Exposure (C/kg)', id: 'radexpckg', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('C/kg') },
            { name: 'roentgen (R)', id: 'radr', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('R') },
            { name: 'Sievert/hour (Sv/h)', id: 'radsvh', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Sv/h') },
        ],
    },
    {
        name: 'Temperature',
        formats: [
            { name: 'Celsius (°C)', id: 'celsius', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('°C') },
            { name: 'Farenheit (°F)', id: 'farenheit', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('°F') },
            { name: 'Kelvin (K)', id: 'kelvin', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('K') },
        ],
    },
    {
        name: 'Time',
        formats: [
            { name: 'Hertz (1/s)', id: 'hertz', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('Hz') },
            { name: 'nanoseconds (ns)', id: 'ns', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toNanoSeconds"] },
            { name: 'microseconds (µs)', id: 'µs', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toMicroSeconds"] },
            { name: 'milliseconds (ms)', id: 'ms', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toMilliSeconds"] },
            { name: 'seconds (s)', id: 's', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toSeconds"] },
            { name: 'minutes (m)', id: 'm', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toMinutes"] },
            { name: 'hours (h)', id: 'h', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toHours"] },
            { name: 'days (d)', id: 'd', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toDays"] },
            { name: 'duration (ms)', id: 'dtdurationms', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toDurationInMilliseconds"] },
            { name: 'duration (s)', id: 'dtdurations', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toDurationInSeconds"] },
            { name: 'duration (hh:mm:ss)', id: 'dthms', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toDurationInHoursMinutesSeconds"] },
            { name: 'Timeticks (s/100)', id: 'timeticks', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toTimeTicks"] },
            { name: 'clock (ms)', id: 'clockms', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toClockMilliseconds"] },
            { name: 'clock (s)', id: 'clocks', fn: _dateTimeFormatters__WEBPACK_IMPORTED_MODULE_1__["toClockSeconds"] },
        ],
    },
    {
        name: 'Throughput',
        formats: [
            { name: 'counts/sec (cps)', id: 'cps', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('cps') },
            { name: 'ops/sec (ops)', id: 'ops', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('ops') },
            { name: 'requests/sec (rps)', id: 'reqps', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('reqps') },
            { name: 'reads/sec (rps)', id: 'rps', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('rps') },
            { name: 'writes/sec (wps)', id: 'wps', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('wps') },
            { name: 'I/O ops/sec (iops)', id: 'iops', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('iops') },
            { name: 'counts/min (cpm)', id: 'cpm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('cpm') },
            { name: 'ops/min (opm)', id: 'opm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('opm') },
            { name: 'reads/min (rpm)', id: 'rpm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('rpm') },
            { name: 'writes/min (wpm)', id: 'wpm', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["simpleCountUnit"])('wpm') },
        ],
    },
    {
        name: 'Velocity',
        formats: [
            { name: 'metres/second (m/s)', id: 'velocityms', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('m/s') },
            { name: 'kilometers/hour (km/h)', id: 'velocitykmh', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('km/h') },
            { name: 'miles/hour (mph)', id: 'velocitymph', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('mph') },
            { name: 'knot (kn)', id: 'velocityknot', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('kn') },
        ],
    },
    {
        name: 'Volume',
        formats: [
            { name: 'millilitre (mL)', id: 'mlitre', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('L', -1) },
            { name: 'litre (L)', id: 'litre', fn: Object(_symbolFormatters__WEBPACK_IMPORTED_MODULE_3__["decimalSIPrefix"])('L') },
            { name: 'cubic metre', id: 'm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('m³') },
            { name: 'Normal cubic metre', id: 'Nm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('Nm³') },
            { name: 'cubic decimetre', id: 'dm3', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('dm³') },
            { name: 'gallons', id: 'gallons', fn: Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["toFixedUnit"])('gal') },
        ],
    },
]; };


/***/ }),

/***/ "./packages/grafana-ui/src/utils/valueFormats/dateTimeFormatters.ts":
/*!**************************************************************************!*\
  !*** ./packages/grafana-ui/src/utils/valueFormats/dateTimeFormatters.ts ***!
  \**************************************************************************/
/*! exports provided: Interval, toNanoSeconds, toMicroSeconds, toMilliSeconds, trySubstract, toSeconds, toMinutes, toHours, toDays, toDuration, toClock, toDurationInMilliseconds, toDurationInSeconds, toDurationInHoursMinutesSeconds, toTimeTicks, toClockMilliseconds, toClockSeconds, dateTimeAsIso, dateTimeAsUS, dateTimeFromNow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Interval", function() { return Interval; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toNanoSeconds", function() { return toNanoSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMicroSeconds", function() { return toMicroSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMilliSeconds", function() { return toMilliSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trySubstract", function() { return trySubstract; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toSeconds", function() { return toSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMinutes", function() { return toMinutes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toHours", function() { return toHours; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDays", function() { return toDays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDuration", function() { return toDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toClock", function() { return toClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDurationInMilliseconds", function() { return toDurationInMilliseconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDurationInSeconds", function() { return toDurationInSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDurationInHoursMinutesSeconds", function() { return toDurationInHoursMinutesSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimeTicks", function() { return toTimeTicks; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toClockMilliseconds", function() { return toClockMilliseconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toClockSeconds", function() { return toClockSeconds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTimeAsIso", function() { return dateTimeAsIso; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTimeAsUS", function() { return dateTimeAsUS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateTimeFromNow", function() { return dateTimeFromNow; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _valueFormats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./valueFormats */ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts");
var _a;


var Interval;
(function (Interval) {
    Interval["Year"] = "year";
    Interval["Month"] = "month";
    Interval["Week"] = "week";
    Interval["Day"] = "day";
    Interval["Hour"] = "hour";
    Interval["Minute"] = "minute";
    Interval["Second"] = "second";
    Interval["Millisecond"] = "millisecond";
})(Interval || (Interval = {}));
var INTERVALS_IN_SECONDS = (_a = {},
    _a[Interval.Year] = 31536000,
    _a[Interval.Month] = 2592000,
    _a[Interval.Week] = 604800,
    _a[Interval.Day] = 86400,
    _a[Interval.Hour] = 3600,
    _a[Interval.Minute] = 60,
    _a[Interval.Second] = 1,
    _a[Interval.Millisecond] = 0.001,
    _a);
function toNanoSeconds(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    if (Math.abs(size) < 1000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' ns';
    }
    else if (Math.abs(size) < 1000000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1000, decimals, scaledDecimals, 3, ' µs');
    }
    else if (Math.abs(size) < 1000000000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1000000, decimals, scaledDecimals, 6, ' ms');
    }
    else if (Math.abs(size) < 60000000000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1000000000, decimals, scaledDecimals, 9, ' s');
    }
    else {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 60000000000, decimals, scaledDecimals, 12, ' min');
    }
}
function toMicroSeconds(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    if (Math.abs(size) < 1000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' µs';
    }
    else if (Math.abs(size) < 1000000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1000, decimals, scaledDecimals, 3, ' ms');
    }
    else {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1000000, decimals, scaledDecimals, 6, ' s');
    }
}
function toMilliSeconds(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    if (Math.abs(size) < 1000) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' ms';
    }
    else if (Math.abs(size) < 60000) {
        // Less than 1 min
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1000, decimals, scaledDecimals, 3, ' s');
    }
    else if (Math.abs(size) < 3600000) {
        // Less than 1 hour, divide in minutes
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 60000, decimals, scaledDecimals, 5, ' min');
    }
    else if (Math.abs(size) < 86400000) {
        // Less than one day, divide in hours
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 3600000, decimals, scaledDecimals, 7, ' hour');
    }
    else if (Math.abs(size) < 31536000000) {
        // Less than one year, divide in days
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 86400000, decimals, scaledDecimals, 8, ' day');
    }
    return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 31536000000, decimals, scaledDecimals, 10, ' year');
}
function trySubstract(value1, value2) {
    if (value1 !== null && value1 !== undefined && value2 !== null && value2 !== undefined) {
        return value1 - value2;
    }
    return undefined;
}
function toSeconds(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    // Less than 1 µs, divide in ns
    if (Math.abs(size) < 0.000001) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size * 1e9, decimals, trySubstract(scaledDecimals, decimals), -9, ' ns');
    }
    // Less than 1 ms, divide in µs
    if (Math.abs(size) < 0.001) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size * 1e6, decimals, trySubstract(scaledDecimals, decimals), -6, ' µs');
    }
    // Less than 1 second, divide in ms
    if (Math.abs(size) < 1) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size * 1e3, decimals, trySubstract(scaledDecimals, decimals), -3, ' ms');
    }
    if (Math.abs(size) < 60) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' s';
    }
    else if (Math.abs(size) < 3600) {
        // Less than 1 hour, divide in minutes
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 60, decimals, scaledDecimals, 1, ' min');
    }
    else if (Math.abs(size) < 86400) {
        // Less than one day, divide in hours
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 3600, decimals, scaledDecimals, 4, ' hour');
    }
    else if (Math.abs(size) < 604800) {
        // Less than one week, divide in days
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 86400, decimals, scaledDecimals, 5, ' day');
    }
    else if (Math.abs(size) < 31536000) {
        // Less than one year, divide in week
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 604800, decimals, scaledDecimals, 6, ' week');
    }
    return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 3.15569e7, decimals, scaledDecimals, 7, ' year');
}
function toMinutes(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    if (Math.abs(size) < 60) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' min';
    }
    else if (Math.abs(size) < 1440) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 60, decimals, scaledDecimals, 2, ' hour');
    }
    else if (Math.abs(size) < 10080) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 1440, decimals, scaledDecimals, 3, ' day');
    }
    else if (Math.abs(size) < 604800) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 10080, decimals, scaledDecimals, 4, ' week');
    }
    else {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 5.25948e5, decimals, scaledDecimals, 5, ' year');
    }
}
function toHours(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    if (Math.abs(size) < 24) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' hour';
    }
    else if (Math.abs(size) < 168) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 24, decimals, scaledDecimals, 2, ' day');
    }
    else if (Math.abs(size) < 8760) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 168, decimals, scaledDecimals, 3, ' week');
    }
    else {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 8760, decimals, scaledDecimals, 4, ' year');
    }
}
function toDays(size, decimals, scaledDecimals) {
    if (size === null) {
        return '';
    }
    if (Math.abs(size) < 7) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixed"])(size, decimals) + ' day';
    }
    else if (Math.abs(size) < 365) {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 7, decimals, scaledDecimals, 2, ' week');
    }
    else {
        return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_1__["toFixedScaled"])(size / 365, decimals, scaledDecimals, 3, ' year');
    }
}
function toDuration(size, decimals, timeScale) {
    if (size === null) {
        return '';
    }
    if (size === 0) {
        return '0 ' + timeScale + 's';
    }
    if (size < 0) {
        return toDuration(-size, decimals, timeScale) + ' ago';
    }
    var units = [
        { long: Interval.Year },
        { long: Interval.Month },
        { long: Interval.Week },
        { long: Interval.Day },
        { long: Interval.Hour },
        { long: Interval.Minute },
        { long: Interval.Second },
        { long: Interval.Millisecond },
    ];
    // convert $size to milliseconds
    // intervals_in_seconds uses seconds (duh), convert them to milliseconds here to minimize floating point errors
    size *= INTERVALS_IN_SECONDS[timeScale] * 1000;
    var strings = [];
    // after first value >= 1 print only $decimals more
    var decrementDecimals = false;
    var decimalsCount = 0;
    if (decimals !== null || decimals !== undefined) {
        decimalsCount = decimals;
    }
    for (var i = 0; i < units.length && decimalsCount >= 0; i++) {
        var interval = INTERVALS_IN_SECONDS[units[i].long] * 1000;
        var value = size / interval;
        if (value >= 1 || decrementDecimals) {
            decrementDecimals = true;
            var floor = Math.floor(value);
            var unit = units[i].long + (floor !== 1 ? 's' : '');
            strings.push(floor + ' ' + unit);
            size = size % interval;
            decimalsCount--;
        }
    }
    return strings.join(', ');
}
function toClock(size, decimals) {
    if (size === null) {
        return '';
    }
    // < 1 second
    if (size < 1000) {
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(size).format('SSS\\m\\s');
    }
    // < 1 minute
    if (size < 60000) {
        var format_1 = 'ss\\s:SSS\\m\\s';
        if (decimals === 0) {
            format_1 = 'ss\\s';
        }
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(size).format(format_1);
    }
    // < 1 hour
    if (size < 3600000) {
        var format_2 = 'mm\\m:ss\\s:SSS\\m\\s';
        if (decimals === 0) {
            format_2 = 'mm\\m';
        }
        else if (decimals === 1) {
            format_2 = 'mm\\m:ss\\s';
        }
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(size).format(format_2);
    }
    var format = 'mm\\m:ss\\s:SSS\\m\\s';
    var hours = ('0' + Math.floor(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toDuration"])(size, 'milliseconds').asHours())).slice(-2) + "h";
    if (decimals === 0) {
        format = '';
    }
    else if (decimals === 1) {
        format = 'mm\\m';
    }
    else if (decimals === 2) {
        format = 'mm\\m:ss\\s';
    }
    return format ? hours + ":" + Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(size).format(format) : hours;
}
function toDurationInMilliseconds(size, decimals) {
    return toDuration(size, decimals, Interval.Millisecond);
}
function toDurationInSeconds(size, decimals) {
    return toDuration(size, decimals, Interval.Second);
}
function toDurationInHoursMinutesSeconds(size) {
    if (size < 0) {
        return toDurationInHoursMinutesSeconds(-size) + ' ago';
    }
    var strings = [];
    var numHours = Math.floor(size / 3600);
    var numMinutes = Math.floor((size % 3600) / 60);
    var numSeconds = Math.floor((size % 3600) % 60);
    numHours > 9 ? strings.push('' + numHours) : strings.push('0' + numHours);
    numMinutes > 9 ? strings.push('' + numMinutes) : strings.push('0' + numMinutes);
    numSeconds > 9 ? strings.push('' + numSeconds) : strings.push('0' + numSeconds);
    return strings.join(':');
}
function toTimeTicks(size, decimals, scaledDecimals) {
    return toSeconds(size / 100, decimals, scaledDecimals);
}
function toClockMilliseconds(size, decimals) {
    return toClock(size, decimals);
}
function toClockSeconds(size, decimals) {
    return toClock(size * 1000, decimals);
}
function dateTimeAsIso(value, decimals, scaledDecimals, isUtc) {
    var time = isUtc ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(value) : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])(value);
    if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])().isSame(value, 'day')) {
        return time.format('HH:mm:ss');
    }
    return time.format('YYYY-MM-DD HH:mm:ss');
}
function dateTimeAsUS(value, decimals, scaledDecimals, isUtc) {
    var time = isUtc ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(value) : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])(value);
    if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])().isSame(value, 'day')) {
        return time.format('h:mm:ss a');
    }
    return time.format('MM/DD/YYYY h:mm:ss a');
}
function dateTimeFromNow(value, decimals, scaledDecimals, isUtc) {
    var time = isUtc ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(value) : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["dateTime"])(value);
    return time.fromNow();
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/valueFormats/symbolFormatters.ts":
/*!************************************************************************!*\
  !*** ./packages/grafana-ui/src/utils/valueFormats/symbolFormatters.ts ***!
  \************************************************************************/
/*! exports provided: currency, binarySIPrefix, decimalSIPrefix */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currency", function() { return currency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "binarySIPrefix", function() { return binarySIPrefix; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decimalSIPrefix", function() { return decimalSIPrefix; });
/* harmony import */ var _valueFormats__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./valueFormats */ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts");

function currency(symbol) {
    var units = ['', 'K', 'M', 'B', 'T'];
    var scaler = Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["scaledUnits"])(1000, units);
    return function (size, decimals, scaledDecimals) {
        if (size === null) {
            return '';
        }
        var scaled = scaler(size, decimals, scaledDecimals);
        return symbol + scaled;
    };
}
function binarySIPrefix(unit, offset) {
    if (offset === void 0) { offset = 0; }
    var prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'].slice(offset);
    var units = prefixes.map(function (p) {
        return ' ' + p + unit;
    });
    return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["scaledUnits"])(1024, units);
}
function decimalSIPrefix(unit, offset) {
    if (offset === void 0) { offset = 0; }
    var prefixes = ['n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
    prefixes = prefixes.slice(3 + (offset || 0));
    var units = prefixes.map(function (p) {
        return ' ' + p + unit;
    });
    return Object(_valueFormats__WEBPACK_IMPORTED_MODULE_0__["scaledUnits"])(1000, units);
}


/***/ }),

/***/ "./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts":
/*!********************************************************************!*\
  !*** ./packages/grafana-ui/src/utils/valueFormats/valueFormats.ts ***!
  \********************************************************************/
/*! exports provided: toFixed, toFixedScaled, toFixedUnit, scaledUnits, locale, simpleCountUnit, getValueFormat, getValueFormatterIndex, getValueFormats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toFixed", function() { return toFixed; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toFixedScaled", function() { return toFixedScaled; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toFixedUnit", function() { return toFixedUnit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scaledUnits", function() { return scaledUnits; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "locale", function() { return locale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "simpleCountUnit", function() { return simpleCountUnit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValueFormat", function() { return getValueFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValueFormatterIndex", function() { return getValueFormatterIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValueFormats", function() { return getValueFormats; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _categories__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./categories */ "./packages/grafana-ui/src/utils/valueFormats/categories.ts");


// Globals & formats cache
var categories = [];
var index = {};
var hasBuiltIndex = false;
function toFixed(value, decimals) {
    if (value === null) {
        return '';
    }
    if (value === Number.NEGATIVE_INFINITY) {
        return '-Inf';
    }
    if (value === Number.POSITIVE_INFINITY) {
        return 'Inf';
    }
    var factor = decimals ? Math.pow(10, Math.max(0, decimals)) : 1;
    var formatted = String(Math.round(value * factor) / factor);
    // if exponent return directly
    if (formatted.indexOf('e') !== -1 || value === 0) {
        return formatted;
    }
    // If tickDecimals was specified, ensure that we have exactly that
    // much precision; otherwise default to the value's own precision.
    if (decimals != null) {
        var decimalPos = formatted.indexOf('.');
        var precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1;
        if (precision < decimals) {
            return (precision ? formatted : formatted + '.') + String(factor).substr(1, decimals - precision);
        }
    }
    return formatted;
}
function toFixedScaled(value, decimals, scaledDecimals, additionalDecimals, ext) {
    if (scaledDecimals === null || scaledDecimals === undefined) {
        return toFixed(value, decimals) + ext;
    }
    else {
        return toFixed(value, scaledDecimals + additionalDecimals) + ext;
    }
    return toFixed(value, decimals) + ext;
}
function toFixedUnit(unit) {
    return function (size, decimals) {
        if (size === null) {
            return '';
        }
        return toFixed(size, decimals) + ' ' + unit;
    };
}
// Formatter which scales the unit string geometrically according to the given
// numeric factor. Repeatedly scales the value down by the factor until it is
// less than the factor in magnitude, or the end of the array is reached.
function scaledUnits(factor, extArray) {
    return function (size, decimals, scaledDecimals) {
        if (size === null) {
            return '';
        }
        var steps = 0;
        var limit = extArray.length;
        while (Math.abs(size) >= factor) {
            steps++;
            size /= factor;
            if (steps >= limit) {
                return 'NA';
            }
        }
        if (steps > 0 && scaledDecimals !== null && scaledDecimals !== undefined) {
            decimals = scaledDecimals + 3 * steps;
        }
        return toFixed(size, decimals) + extArray[steps];
    };
}
function locale(value, decimals) {
    if (value == null) {
        return '';
    }
    return value.toLocaleString(undefined, { maximumFractionDigits: decimals });
}
function simpleCountUnit(symbol) {
    var units = ['', 'K', 'M', 'B', 'T'];
    var scaler = scaledUnits(1000, units);
    return function (size, decimals, scaledDecimals) {
        if (size === null) {
            return '';
        }
        var scaled = scaler(size, decimals, scaledDecimals);
        return scaled + ' ' + symbol;
    };
}
function buildFormats() {
    var e_1, _a, e_2, _b;
    categories = Object(_categories__WEBPACK_IMPORTED_MODULE_1__["getCategories"])();
    try {
        for (var categories_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](categories), categories_1_1 = categories_1.next(); !categories_1_1.done; categories_1_1 = categories_1.next()) {
            var cat = categories_1_1.value;
            try {
                for (var _c = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](cat.formats)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var format = _d.value;
                    index[format.id] = format.fn;
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (categories_1_1 && !categories_1_1.done && (_a = categories_1.return)) _a.call(categories_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    hasBuiltIndex = true;
}
function getValueFormat(id) {
    if (!hasBuiltIndex) {
        buildFormats();
    }
    return index[id];
}
function getValueFormatterIndex() {
    if (!hasBuiltIndex) {
        buildFormats();
    }
    return index;
}
function getValueFormats() {
    if (!hasBuiltIndex) {
        buildFormats();
    }
    return categories.map(function (cat) {
        return {
            text: cat.name,
            submenu: cat.formats.map(function (format) {
                return {
                    text: format.name,
                    value: format.id,
                };
            }),
        };
    });
}


/***/ }),

/***/ "./public/app/app.ts":
/*!***************************!*\
  !*** ./public/app/app.ts ***!
  \***************************/
/*! exports provided: GrafanaApp, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GrafanaApp", function() { return GrafanaApp; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _babel_polyfill__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/polyfill */ "./node_modules/@babel/polyfill/lib/index.js");
/* harmony import */ var _babel_polyfill__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_polyfill__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! file-saver */ "./node_modules/file-saver/FileSaver.js");
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var angular_route__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! angular-route */ "./node_modules/angular-route/index.js");
/* harmony import */ var angular_route__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(angular_route__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var angular_sanitize__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! angular-sanitize */ "./node_modules/angular-sanitize/index.js");
/* harmony import */ var angular_sanitize__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(angular_sanitize__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var angular_native_dragdrop__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! angular-native-dragdrop */ "./node_modules/angular-native-dragdrop/index.js");
/* harmony import */ var angular_native_dragdrop__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(angular_native_dragdrop__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var angular_bindonce__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! angular-bindonce */ "./node_modules/angular-bindonce/bindonce.js");
/* harmony import */ var angular_bindonce__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(angular_bindonce__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var vendor_bootstrap_bootstrap__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! vendor/bootstrap/bootstrap */ "./public/vendor/bootstrap/bootstrap.js");
/* harmony import */ var vendor_bootstrap_bootstrap__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(vendor_bootstrap_bootstrap__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var vendor_angular_other_angular_strap__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! vendor/angular-other/angular-strap */ "./public/vendor/angular-other/angular-strap.js");
/* harmony import */ var vendor_angular_other_angular_strap__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(vendor_angular_other_angular_strap__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_utils_scrollbar__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! app/core/utils/scrollbar */ "./public/app/core/utils/scrollbar.ts");
/* harmony import */ var app_features_plugins_plugin_loader__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! app/features/plugins/plugin_loader */ "./public/app/features/plugins/plugin_loader.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var app_routes_routes__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! app/routes/routes */ "./public/app/routes/routes.ts");
/* harmony import */ var app_routes_GrafanaCtrl__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! app/routes/GrafanaCtrl */ "./public/app/routes/GrafanaCtrl.ts");
/* harmony import */ var app_features_all__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! app/features/all */ "./public/app/features/all.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

















// @ts-ignore ignoring this for now, otherwise we would have to extend _ interface with move



// add move to lodash for backward compatabiltiy
// @ts-ignore
lodash__WEBPACK_IMPORTED_MODULE_3___default.a.move = function (array, fromIndex, toIndex) {
    array.splice(toIndex, 0, array.splice(fromIndex, 1)[0]);
    return array;
};







// import symlinked extensions
var extensionsIndex = __webpack_require__("./public/app sync recursive extensions\\/index.ts");
extensionsIndex.keys().forEach(function (key) {
    extensionsIndex(key);
});
var GrafanaApp = /** @class */ (function () {
    function GrafanaApp() {
        Object(app_core_utils_scrollbar__WEBPACK_IMPORTED_MODULE_15__["addClassIfNoOverlayScrollbar"])('no-overlay-scrollbar');
        this.preBootModules = [];
        this.registerFunctions = {};
        this.ngModuleDependencies = [];
    }
    GrafanaApp.prototype.useModule = function (module) {
        if (this.preBootModules) {
            this.preBootModules.push(module);
        }
        else {
            lodash__WEBPACK_IMPORTED_MODULE_3___default.a.extend(module, this.registerFunctions);
        }
        this.ngModuleDependencies.push(module.name);
        return module;
    };
    GrafanaApp.prototype.init = function () {
        var e_1, _a;
        var _this = this;
        var app = angular__WEBPACK_IMPORTED_MODULE_5___default.a.module('grafana', []);
        Object(_grafana_data__WEBPACK_IMPORTED_MODULE_22__["setLocale"])(app_core_config__WEBPACK_IMPORTED_MODULE_14__["default"].bootData.user.locale);
        Object(_grafana_data__WEBPACK_IMPORTED_MODULE_22__["setMarkdownOptions"])({ sanitize: !app_core_config__WEBPACK_IMPORTED_MODULE_14__["default"].disableSanitizeHtml });
        app.config(function ($locationProvider, $controllerProvider, $compileProvider, $filterProvider, $httpProvider, $provide) {
            // pre assing bindings before constructor calls
            $compileProvider.preAssignBindingsEnabled(true);
            if (app_core_config__WEBPACK_IMPORTED_MODULE_14__["default"].buildInfo.env !== 'development') {
                $compileProvider.debugInfoEnabled(false);
            }
            $httpProvider.useApplyAsync(true);
            _this.registerFunctions.controller = $controllerProvider.register;
            _this.registerFunctions.directive = $compileProvider.directive;
            _this.registerFunctions.factory = $provide.factory;
            _this.registerFunctions.service = $provide.service;
            _this.registerFunctions.filter = $filterProvider.register;
            $provide.decorator('$http', [
                '$delegate',
                '$templateCache',
                function ($delegate, $templateCache) {
                    var get = $delegate.get;
                    $delegate.get = function (url, config) {
                        if (url.match(/\.html$/)) {
                            // some template's already exist in the cache
                            if (!$templateCache.get(url)) {
                                url += '?v=' + new Date().getTime();
                            }
                        }
                        return get(url, config);
                    };
                    return $delegate;
                },
            ]);
        });
        this.ngModuleDependencies = [
            'grafana.core',
            'ngRoute',
            'ngSanitize',
            '$strap.directives',
            'ang-drag-drop',
            'grafana',
            'pasvaz.bindonce',
            'react',
        ];
        // makes it possible to add dynamic stuff
        lodash__WEBPACK_IMPORTED_MODULE_3___default.a.each(app_core_core_module__WEBPACK_IMPORTED_MODULE_17__["angularModules"], function (m) {
            _this.useModule(m);
        });
        // register react angular wrappers
        app_core_core_module__WEBPACK_IMPORTED_MODULE_17__["coreModule"].config(app_routes_routes__WEBPACK_IMPORTED_MODULE_19__["setupAngularRoutes"]);
        Object(app_core_core__WEBPACK_IMPORTED_MODULE_18__["registerAngularDirectives"])();
        // disable tool tip animation
        jquery__WEBPACK_IMPORTED_MODULE_4___default.a.fn.tooltip.defaults.animation = false;
        // bootstrap the app
        angular__WEBPACK_IMPORTED_MODULE_5___default.a.bootstrap(document, this.ngModuleDependencies).invoke(function () {
            lodash__WEBPACK_IMPORTED_MODULE_3___default.a.each(_this.preBootModules, function (module) {
                lodash__WEBPACK_IMPORTED_MODULE_3___default.a.extend(module, _this.registerFunctions);
            });
            _this.preBootModules = null;
        });
        try {
            // Preload selected app plugins
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](app_core_config__WEBPACK_IMPORTED_MODULE_14__["default"].pluginsToPreload), _c = _b.next(); !_c.done; _c = _b.next()) {
                var modulePath = _c.value;
                Object(app_features_plugins_plugin_loader__WEBPACK_IMPORTED_MODULE_16__["importPluginModule"])(modulePath);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    return GrafanaApp;
}());

/* harmony default export */ __webpack_exports__["default"] = (new GrafanaApp());


/***/ }),

/***/ "./public/app/core/actions/appNotification.ts":
/*!****************************************************!*\
  !*** ./public/app/core/actions/appNotification.ts ***!
  \****************************************************/
/*! exports provided: ActionTypes, clearAppNotification, notifyApp */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearAppNotification", function() { return clearAppNotification; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notifyApp", function() { return notifyApp; });
var ActionTypes;
(function (ActionTypes) {
    ActionTypes["AddAppNotification"] = "ADD_APP_NOTIFICATION";
    ActionTypes["ClearAppNotification"] = "CLEAR_APP_NOTIFICATION";
})(ActionTypes || (ActionTypes = {}));
var clearAppNotification = function (appNotificationId) { return ({
    type: ActionTypes.ClearAppNotification,
    payload: appNotificationId,
}); };
var notifyApp = function (appNotification) { return ({
    type: ActionTypes.AddAppNotification,
    payload: appNotification,
}); };


/***/ }),

/***/ "./public/app/core/actions/application.ts":
/*!************************************************!*\
  !*** ./public/app/core/actions/application.ts ***!
  \************************************************/
/*! exports provided: toggleLogActions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggleLogActions", function() { return toggleLogActions; });
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");

var toggleLogActions = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_0__["noPayloadActionCreatorFactory"])('TOGGLE_LOG_ACTIONS').create();


/***/ }),

/***/ "./public/app/core/actions/index.ts":
/*!******************************************!*\
  !*** ./public/app/core/actions/index.ts ***!
  \******************************************/
/*! exports provided: updateLocation, updateNavIndex, UpdateNavIndexAction, notifyApp, clearAppNotification */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _location__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./location */ "./public/app/core/actions/location.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "updateLocation", function() { return _location__WEBPACK_IMPORTED_MODULE_0__["updateLocation"]; });

/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./navModel */ "./public/app/core/actions/navModel.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "updateNavIndex", function() { return _navModel__WEBPACK_IMPORTED_MODULE_1__["updateNavIndex"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UpdateNavIndexAction", function() { return _navModel__WEBPACK_IMPORTED_MODULE_1__["UpdateNavIndexAction"]; });

/* harmony import */ var _appNotification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./appNotification */ "./public/app/core/actions/appNotification.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "notifyApp", function() { return _appNotification__WEBPACK_IMPORTED_MODULE_2__["notifyApp"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "clearAppNotification", function() { return _appNotification__WEBPACK_IMPORTED_MODULE_2__["clearAppNotification"]; });







/***/ }),

/***/ "./public/app/core/actions/location.ts":
/*!*********************************************!*\
  !*** ./public/app/core/actions/location.ts ***!
  \*********************************************/
/*! exports provided: updateLocation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateLocation", function() { return updateLocation; });
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");

var updateLocation = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('UPDATE_LOCATION').create();


/***/ }),

/***/ "./public/app/core/actions/navModel.ts":
/*!*********************************************!*\
  !*** ./public/app/core/actions/navModel.ts ***!
  \*********************************************/
/*! exports provided: ActionTypes, updateNavIndex */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateNavIndex", function() { return updateNavIndex; });
var ActionTypes;
(function (ActionTypes) {
    ActionTypes["UpdateNavIndex"] = "UPDATE_NAV_INDEX";
})(ActionTypes || (ActionTypes = {}));
var updateNavIndex = function (item) { return ({
    type: ActionTypes.UpdateNavIndex,
    payload: item,
}); };


/***/ }),

/***/ "./public/app/core/angular_wrappers.ts":
/*!*********************************************!*\
  !*** ./public/app/core/angular_wrappers.ts ***!
  \*********************************************/
/*! exports provided: registerAngularDirectives */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerAngularDirectives", function() { return registerAngularDirectives; });
/* harmony import */ var app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/utils/react2angular */ "./public/app/core/utils/react2angular.ts");
/* harmony import */ var app_plugins_datasource_stackdriver_components_QueryEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/plugins/datasource/stackdriver/components/QueryEditor */ "./public/app/plugins/datasource/stackdriver/components/QueryEditor.tsx");
/* harmony import */ var app_plugins_datasource_stackdriver_components_AnnotationQueryEditor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/plugins/datasource/stackdriver/components/AnnotationQueryEditor */ "./public/app/plugins/datasource/stackdriver/components/AnnotationQueryEditor.tsx");
/* harmony import */ var _components_PageHeader_PageHeader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/PageHeader/PageHeader */ "./public/app/core/components/PageHeader/PageHeader.tsx");
/* harmony import */ var _components_EmptyListCTA_EmptyListCTA__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./components/EmptyListCTA/EmptyListCTA */ "./public/app/core/components/EmptyListCTA/EmptyListCTA.tsx");
/* harmony import */ var _components_TagFilter_TagFilter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./components/TagFilter/TagFilter */ "./public/app/core/components/TagFilter/TagFilter.tsx");
/* harmony import */ var _components_sidemenu_SideMenu__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./components/sidemenu/SideMenu */ "./public/app/core/components/sidemenu/SideMenu.tsx");
/* harmony import */ var _components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./components/Select/MetricSelect */ "./public/app/core/components/Select/MetricSelect.tsx");
/* harmony import */ var _components_AppNotifications_AppNotificationList__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./components/AppNotifications/AppNotificationList */ "./public/app/core/components/AppNotifications/AppNotificationList.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_plugins_datasource_graphite_FunctionEditor__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! app/plugins/datasource/graphite/FunctionEditor */ "./public/app/plugins/datasource/graphite/FunctionEditor.tsx");
/* harmony import */ var _components_search_SearchField__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./components/search/SearchField */ "./public/app/core/components/search/SearchField.tsx");
/* harmony import */ var app_plugins_panel_graph_GraphContextMenu__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/plugins/panel/graph/GraphContextMenu */ "./public/app/plugins/panel/graph/GraphContextMenu.tsx");
/* harmony import */ var app_features_profile_ReactProfileWrapper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! app/features/profile/ReactProfileWrapper */ "./public/app/features/profile/ReactProfileWrapper.tsx");
/* harmony import */ var _plugins_datasource_loki_components_AnnotationsQueryEditor__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../plugins/datasource/loki/components/AnnotationsQueryEditor */ "./public/app/plugins/datasource/loki/components/AnnotationsQueryEditor.tsx");















function registerAngularDirectives() {
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('sidemenu', _components_sidemenu_SideMenu__WEBPACK_IMPORTED_MODULE_6__["SideMenu"], []);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('functionEditor', app_plugins_datasource_graphite_FunctionEditor__WEBPACK_IMPORTED_MODULE_10__["FunctionEditor"], ['func', 'onRemove', 'onMoveLeft', 'onMoveRight']);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('appNotificationsList', _components_AppNotifications_AppNotificationList__WEBPACK_IMPORTED_MODULE_8__["default"], []);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('pageHeader', _components_PageHeader_PageHeader__WEBPACK_IMPORTED_MODULE_3__["default"], ['model', 'noTabs']);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('emptyListCta', _components_EmptyListCTA_EmptyListCTA__WEBPACK_IMPORTED_MODULE_4__["default"], [
        'title',
        'buttonIcon',
        'buttonLink',
        'buttonTitle',
        ['onClick', { watchDepth: 'reference', wrapApply: true }],
        'proTip',
        'proTipLink',
        'proTipLinkTitle',
        'proTipTarget',
        'infoBox',
        'infoBoxTitle',
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('searchField', _components_search_SearchField__WEBPACK_IMPORTED_MODULE_11__["SearchField"], [
        'query',
        'autoFocus',
        ['onChange', { watchDepth: 'reference' }],
        ['onKeyDown', { watchDepth: 'reference' }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('tagFilter', _components_TagFilter_TagFilter__WEBPACK_IMPORTED_MODULE_5__["TagFilter"], [
        'tags',
        ['onChange', { watchDepth: 'reference' }],
        ['tagOptions', { watchDepth: 'reference' }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('colorPicker', _grafana_ui__WEBPACK_IMPORTED_MODULE_9__["ColorPicker"], [
        'color',
        ['onChange', { watchDepth: 'reference', wrapApply: true }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('seriesColorPickerPopover', _grafana_ui__WEBPACK_IMPORTED_MODULE_9__["SeriesColorPickerPopoverWithTheme"], [
        'color',
        'series',
        'onColorChange',
        'onToggleAxis',
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('metricSelect', _components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_7__["MetricSelect"], [
        'options',
        'onChange',
        'value',
        'isSearchable',
        'className',
        'placeholder',
        ['variables', { watchDepth: 'reference' }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('stackdriverQueryEditor', app_plugins_datasource_stackdriver_components_QueryEditor__WEBPACK_IMPORTED_MODULE_1__["QueryEditor"], [
        'target',
        'onQueryChange',
        'onExecuteQuery',
        ['events', { watchDepth: 'reference' }],
        ['datasource', { watchDepth: 'reference' }],
        ['templateSrv', { watchDepth: 'reference' }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('stackdriverAnnotationQueryEditor', app_plugins_datasource_stackdriver_components_AnnotationQueryEditor__WEBPACK_IMPORTED_MODULE_2__["AnnotationQueryEditor"], [
        'target',
        'onQueryChange',
        'onExecuteQuery',
        ['datasource', { watchDepth: 'reference' }],
        ['templateSrv', { watchDepth: 'reference' }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('secretFormField', _grafana_ui__WEBPACK_IMPORTED_MODULE_9__["SecretFormField"], [
        'value',
        'isConfigured',
        'inputWidth',
        'labelWidth',
        ['onReset', { watchDepth: 'reference', wrapApply: true }],
        ['onChange', { watchDepth: 'reference', wrapApply: true }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('graphContextMenu', app_plugins_panel_graph_GraphContextMenu__WEBPACK_IMPORTED_MODULE_12__["GraphContextMenu"], [
        'x',
        'y',
        'items',
        ['onClose', { watchDepth: 'reference', wrapApply: true }],
        ['getContextMenuSource', { watchDepth: 'reference', wrapApply: true }],
        ['formatSourceDate', { watchDepth: 'reference', wrapApply: true }],
    ]);
    // We keep the drilldown terminology here because of as using data-* directive
    // being in conflict with HTML data attributes
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('drilldownLinksEditor', _grafana_ui__WEBPACK_IMPORTED_MODULE_9__["DataLinksEditor"], [
        'value',
        'suggestions',
        ['onChange', { watchDepth: 'reference', wrapApply: true }],
    ]);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('reactProfileWrapper', app_features_profile_ReactProfileWrapper__WEBPACK_IMPORTED_MODULE_13__["default"], []);
    Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_0__["react2AngularDirective"])('lokiAnnotationsQueryEditor', _plugins_datasource_loki_components_AnnotationsQueryEditor__WEBPACK_IMPORTED_MODULE_14__["LokiAnnotationsQueryEditor"], [
        'expr',
        'onChange',
        ['datasource', { watchDepth: 'reference' }],
    ]);
}


/***/ }),

/***/ "./public/app/core/app_events.ts":
/*!***************************************!*\
  !*** ./public/app/core/app_events.ts ***!
  \***************************************/
/*! exports provided: appEvents, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appEvents", function() { return appEvents; });
/* harmony import */ var _utils_emitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/emitter */ "./public/app/core/utils/emitter.ts");

var appEvents = new _utils_emitter__WEBPACK_IMPORTED_MODULE_0__["Emitter"]();
/* harmony default export */ __webpack_exports__["default"] = (appEvents);


/***/ }),

/***/ "./public/app/core/components/AlertBox/AlertBox.tsx":
/*!**********************************************************!*\
  !*** ./public/app/core/components/AlertBox/AlertBox.tsx ***!
  \**********************************************************/
/*! exports provided: AlertBox */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertBox", function() { return AlertBox; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");



function getIconFromSeverity(severity) {
    switch (severity) {
        case app_types__WEBPACK_IMPORTED_MODULE_2__["AppNotificationSeverity"].Error: {
            return 'fa fa-exclamation-triangle';
        }
        case app_types__WEBPACK_IMPORTED_MODULE_2__["AppNotificationSeverity"].Warning: {
            return 'fa fa-exclamation-triangle';
        }
        case app_types__WEBPACK_IMPORTED_MODULE_2__["AppNotificationSeverity"].Info: {
            return 'fa fa-info-circle';
        }
        case app_types__WEBPACK_IMPORTED_MODULE_2__["AppNotificationSeverity"].Success: {
            return 'fa fa-check';
        }
        default:
            return '';
    }
}
var AlertBox = function (_a) {
    var title = _a.title, icon = _a.icon, body = _a.body, severity = _a.severity, onClose = _a.onClose;
    var alertClass = classnames__WEBPACK_IMPORTED_MODULE_1___default()('alert', "alert-" + severity);
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: alertClass },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-icon" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: icon || getIconFromSeverity(severity) })),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-body" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-title" }, title),
            body && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "alert-text" }, body)),
        onClose && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { type: "button", className: "alert-close", onClick: onClose },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa fa-remove" })))));
};


/***/ }),

/***/ "./public/app/core/components/Animations/SlideDown.tsx":
/*!*************************************************************!*\
  !*** ./public/app/core/components/Animations/SlideDown.tsx ***!
  \*************************************************************/
/*! exports provided: defaultStyle, SlideDown */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultStyle", function() { return defaultStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SlideDown", function() { return SlideDown; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-transition-group/Transition */ "./node_modules/react-transition-group/Transition.js");
/* harmony import */ var react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_2__);



// When animating using max-height we need to use a static value.
// If this is not enough, pass in <SlideDown maxHeight="....
var defaultMaxHeight = '200px';
var defaultDuration = 200;
var defaultStyle = {
    transition: "max-height " + defaultDuration + "ms ease-in-out",
    overflow: 'hidden',
};
var SlideDown = function (_a) {
    var children = _a.children, inProp = _a.in, _b = _a.maxHeight, maxHeight = _b === void 0 ? defaultMaxHeight : _b, _c = _a.style, style = _c === void 0 ? defaultStyle : _c;
    // There are 4 main states a Transition can be in:
    // ENTERING, ENTERED, EXITING, EXITED
    // https://reactcommunity.or[g/react-transition-group/
    var transitionStyles = {
        exited: { maxHeight: 0 },
        entering: { maxHeight: maxHeight },
        entered: { maxHeight: 'unset', overflow: 'visible' },
        exiting: { maxHeight: 0 },
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_transition_group_Transition__WEBPACK_IMPORTED_MODULE_2___default.a, { in: inProp, timeout: defaultDuration }, function (state) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, style, transitionStyles[state]) }, children)); }));
};


/***/ }),

/***/ "./public/app/core/components/AppNotifications/AppNotificationItem.tsx":
/*!*****************************************************************************!*\
  !*** ./public/app/core/components/AppNotifications/AppNotificationItem.tsx ***!
  \*****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../AlertBox/AlertBox */ "./public/app/core/components/AlertBox/AlertBox.tsx");



var AppNotificationItem = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AppNotificationItem, _super);
    function AppNotificationItem() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AppNotificationItem.prototype.shouldComponentUpdate = function (nextProps) {
        return this.props.appNotification.id !== nextProps.appNotification.id;
    };
    AppNotificationItem.prototype.componentDidMount = function () {
        var _a = this.props, appNotification = _a.appNotification, onClearNotification = _a.onClearNotification;
        setTimeout(function () {
            onClearNotification(appNotification.id);
        }, appNotification.timeout);
    };
    AppNotificationItem.prototype.render = function () {
        var _a = this.props, appNotification = _a.appNotification, onClearNotification = _a.onClearNotification;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_2__["AlertBox"], { severity: appNotification.severity, title: appNotification.title, body: appNotification.text, icon: appNotification.icon, onClose: function () { return onClearNotification(appNotification.id); } }));
    };
    return AppNotificationItem;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
/* harmony default export */ __webpack_exports__["default"] = (AppNotificationItem);


/***/ }),

/***/ "./public/app/core/components/AppNotifications/AppNotificationList.tsx":
/*!*****************************************************************************!*\
  !*** ./public/app/core/components/AppNotifications/AppNotificationList.tsx ***!
  \*****************************************************************************/
/*! exports provided: AppNotificationList, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppNotificationList", function() { return AppNotificationList; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var _AppNotificationItem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./AppNotificationItem */ "./public/app/core/components/AppNotifications/AppNotificationItem.tsx");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var app_core_utils_connectWithReduxStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/utils/connectWithReduxStore */ "./public/app/core/utils/connectWithReduxStore.tsx");
/* harmony import */ var _copy_appNotification__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../copy/appNotification */ "./public/app/core/copy/appNotification.ts");







var AppNotificationList = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AppNotificationList, _super);
    function AppNotificationList() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onClearAppNotification = function (id) {
            _this.props.clearAppNotification(id);
        };
        return _this;
    }
    AppNotificationList.prototype.componentDidMount = function () {
        var notifyApp = this.props.notifyApp;
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].on('alert-warning', function (options) { return notifyApp(Object(_copy_appNotification__WEBPACK_IMPORTED_MODULE_6__["createWarningNotification"])(options[0], options[1])); });
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].on('alert-success', function (options) { return notifyApp(Object(_copy_appNotification__WEBPACK_IMPORTED_MODULE_6__["createSuccessNotification"])(options[0], options[1])); });
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].on('alert-error', function (options) { return notifyApp(Object(_copy_appNotification__WEBPACK_IMPORTED_MODULE_6__["createErrorNotification"])(options[0], options[1])); });
    };
    AppNotificationList.prototype.render = function () {
        var _this = this;
        var appNotifications = this.props.appNotifications;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, appNotifications.map(function (appNotification, index) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AppNotificationItem__WEBPACK_IMPORTED_MODULE_3__["default"], { key: appNotification.id + "-" + index, appNotification: appNotification, onClearNotification: function (id) { return _this.onClearAppNotification(id); } }));
        })));
    };
    return AppNotificationList;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var mapStateToProps = function (state) { return ({
    appNotifications: state.appNotifications.appNotifications,
}); };
var mapDispatchToProps = {
    notifyApp: app_core_actions__WEBPACK_IMPORTED_MODULE_4__["notifyApp"],
    clearAppNotification: app_core_actions__WEBPACK_IMPORTED_MODULE_4__["clearAppNotification"],
};
/* harmony default export */ __webpack_exports__["default"] = (Object(app_core_utils_connectWithReduxStore__WEBPACK_IMPORTED_MODULE_5__["connectWithStore"])(AppNotificationList, mapStateToProps, mapDispatchToProps));


/***/ }),

/***/ "./public/app/core/components/EmptyListCTA/EmptyListCTA.tsx":
/*!******************************************************************!*\
  !*** ./public/app/core/components/EmptyListCTA/EmptyListCTA.tsx ***!
  \******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");




var ctaStyle = Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n  text-align: center;\n"], ["\n  text-align: center;\n"])));
var infoBoxStyles = Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n  max-width: 700px;\n  margin: 0 auto;\n"], ["\n  max-width: 700px;\n  margin: 0 auto;\n"])));
var EmptyListCTA = function (_a) {
    var title = _a.title, buttonIcon = _a.buttonIcon, buttonLink = _a.buttonLink, buttonTitle = _a.buttonTitle, onClick = _a.onClick, proTip = _a.proTip, proTipLink = _a.proTipLink, proTipLinkTitle = _a.proTipLinkTitle, proTipTarget = _a.proTipTarget, infoBox = _a.infoBox, infoBoxTitle = _a.infoBoxTitle;
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ThemeContext"]);
    var footer = function () {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            proTip ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: "proTipFooter" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-rocket" }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                    " ProTip: ",
                    proTip,
                    " "),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: proTipLink, target: proTipTarget, className: "text-link" }, proTipLinkTitle))) : (''),
            infoBox ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { key: "infoBoxHtml", className: "grafana-info-box " + infoBoxStyles },
                infoBoxTitle && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", null, infoBoxTitle),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { dangerouslySetInnerHTML: infoBox }))) : ('')));
    };
    var ctaElementClassName = !footer()
        ? Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n        margin-bottom: 20px;\n      "], ["\n        margin-bottom: 20px;\n      "]))) : '';
    var ctaElement = (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["LinkButton"], { size: "lg", onClick: onClick, href: buttonLink, icon: buttonIcon, className: ctaElementClassName }, buttonTitle));
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["CallToActionCard"], { className: ctaStyle, message: title, footer: footer(), callToActionElement: ctaElement, theme: theme }));
};
/* harmony default export */ __webpack_exports__["default"] = (EmptyListCTA);
var templateObject_1, templateObject_2, templateObject_3;


/***/ }),

/***/ "./public/app/core/components/FilterInput/FilterInput.tsx":
/*!****************************************************************!*\
  !*** ./public/app/core/components/FilterInput/FilterInput.tsx ***!
  \****************************************************************/
/*! exports provided: escapeStringForRegex, unEscapeStringFromRegex, FilterInput */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "escapeStringForRegex", function() { return escapeStringForRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unEscapeStringFromRegex", function() { return unEscapeStringFromRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FilterInput", function() { return FilterInput; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var specialChars = ['(', '[', '{', '}', ']', ')', '|', '*', '+', '-', '.', '?', '<', '>', '#', '&', '^', '$'];
var escapeStringForRegex = function (value) {
    if (!value) {
        return value;
    }
    var newValue = specialChars.reduce(function (escaped, currentChar) { return escaped.replace(currentChar, '\\' + currentChar); }, value);
    return newValue;
};
var unEscapeStringFromRegex = function (value) {
    if (!value) {
        return value;
    }
    var newValue = specialChars.reduce(function (escaped, currentChar) { return escaped.replace('\\' + currentChar, currentChar); }, value);
    return newValue;
};
var FilterInput = Object(react__WEBPACK_IMPORTED_MODULE_0__["forwardRef"])(function (props, ref) { return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("label", { className: props.labelClassName },
    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("input", { ref: ref, type: "text", className: props.inputClassName, value: unEscapeStringFromRegex(props.value), onChange: function (event) { return props.onChange(escapeStringForRegex(event.target.value)); }, placeholder: props.placeholder ? props.placeholder : null }),
    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "gf-form-input-icon fa fa-search" }))); });


/***/ }),

/***/ "./public/app/core/components/Footer/Footer.tsx":
/*!******************************************************!*\
  !*** ./public/app/core/components/Footer/Footer.tsx ***!
  \******************************************************/
/*! exports provided: Footer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Footer", function() { return Footer; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


var Footer = react__WEBPACK_IMPORTED_MODULE_0___default.a.memo(function (_a) {
    var appName = _a.appName, buildVersion = _a.buildVersion, buildCommit = _a.buildCommit, newGrafanaVersionExists = _a.newGrafanaVersionExists, newGrafanaVersion = _a.newGrafanaVersion;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("footer", { className: "footer" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "text-center" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "http://docs.grafana.org", target: "_blank", rel: "noopener" },
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-file-code-o" }),
                        " Docs")),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "https://grafana.com/services/support", target: "_blank", rel: "noopener" },
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-support" }),
                        " Support Plans")),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "https://community.grafana.com/", target: "_blank", rel: "noopener" },
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-comments-o" }),
                        " Community")),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "https://grafana.com", target: "_blank", rel: "noopener" }, appName),
                    ' ',
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null,
                        "v",
                        buildVersion,
                        " (commit: ",
                        buildCommit,
                        ")")),
                newGrafanaVersionExists && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["Tooltip"], { placement: "auto", content: newGrafanaVersion },
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "https://grafana.com/get", target: "_blank", rel: "noopener" }, "New version available!"))))))));
});
/* harmony default export */ __webpack_exports__["default"] = (Footer);


/***/ }),

/***/ "./public/app/core/components/LayoutSelector/LayoutSelector.tsx":
/*!**********************************************************************!*\
  !*** ./public/app/core/components/LayoutSelector/LayoutSelector.tsx ***!
  \**********************************************************************/
/*! exports provided: LayoutModes, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LayoutModes", function() { return LayoutModes; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var LayoutModes;
(function (LayoutModes) {
    LayoutModes["Grid"] = "grid";
    LayoutModes["List"] = "list";
})(LayoutModes || (LayoutModes = {}));
var LayoutSelector = function (props) {
    var mode = props.mode, onLayoutModeChanged = props.onLayoutModeChanged;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "layout-selector" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { onClick: function () {
                onLayoutModeChanged(LayoutModes.List);
            }, className: mode === LayoutModes.List ? 'active' : '' },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-list" })),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { onClick: function () {
                onLayoutModeChanged(LayoutModes.Grid);
            }, className: mode === LayoutModes.Grid ? 'active' : '' },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-th" }))));
};
/* harmony default export */ __webpack_exports__["default"] = (LayoutSelector);


/***/ }),

/***/ "./public/app/core/components/Login/ChangePassword.tsx":
/*!*************************************************************!*\
  !*** ./public/app/core/components/Login/ChangePassword.tsx ***!
  \*************************************************************/
/*! exports provided: ChangePassword */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChangePassword", function() { return ChangePassword; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");




var ChangePassword = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ChangePassword, _super);
    function ChangePassword(props) {
        var _this = _super.call(this, props) || this;
        _this.onSubmit = function (e) {
            e.preventDefault();
            var _a = _this.state, newPassword = _a.newPassword, valid = _a.valid;
            if (valid) {
                _this.props.onSubmit(newPassword);
            }
            else {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('alert-warning', ['New passwords do not match', '']);
            }
        };
        _this.onNewPasswordChange = function (e) {
            _this.setState({
                newPassword: e.target.value,
                valid: _this.validate('newPassword', e.target.value),
            });
        };
        _this.onConfirmPasswordChange = function (e) {
            _this.setState({
                confirmNew: e.target.value,
                valid: _this.validate('confirmNew', e.target.value),
            });
        };
        _this.onSkip = function (e) {
            _this.props.onSkip();
        };
        _this.state = {
            newPassword: '',
            confirmNew: '',
            valid: false,
        };
        return _this;
    }
    ChangePassword.prototype.componentDidUpdate = function (prevProps) {
        if (!prevProps.focus && this.props.focus) {
            this.focus();
        }
    };
    ChangePassword.prototype.focus = function () {
        this.userInput.focus();
    };
    ChangePassword.prototype.validate = function (changed, pw) {
        if (changed === 'newPassword') {
            return this.state.confirmNew === pw;
        }
        else if (changed === 'confirmNew') {
            return this.state.newPassword === pw;
        }
        return false;
    };
    ChangePassword.prototype.render = function () {
        var _this = this;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-inner-box", id: "change-password-view" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "text-left login-change-password-info" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", null, "Change Password"),
                "Before you can get started with awesome dashboards we need you to make your account more secure by changing your password.",
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                "You can change your password again later."),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", { className: "login-form-group gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", { type: "password", id: "newPassword", name: "newPassword", className: "gf-form-input login-form-input", required: true, placeholder: "New password", onChange: this.onNewPasswordChange, ref: function (input) {
                            _this.userInput = input;
                        } })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", { type: "password", name: "confirmNew", className: "gf-form-input login-form-input", required: true, "ng-model": "command.confirmNew", placeholder: "Confirm new password", onChange: this.onConfirmPasswordChange })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-button-group login-button-group--right text-right" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Tooltip"], { placement: "bottom", content: "If you skip you will be prompted to change password next time you login." },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "btn btn-link", onClick: this.onSkip }, "Skip")),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { type: "submit", className: "btn btn-large p-x-2 " + (this.state.valid ? 'btn-primary' : 'btn-inverse'), onClick: this.onSubmit, disabled: !this.state.valid }, "Save")))));
    };
    return ChangePassword;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/core/components/Login/LoginCtrl.tsx":
/*!********************************************************!*\
  !*** ./public/app/core/components/Login/LoginCtrl.tsx ***!
  \********************************************************/
/*! exports provided: LoginCtrl, mapStateToProps, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoginCtrl", function() { return LoginCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapStateToProps", function() { return mapStateToProps; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var react_hot_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! react-hot-loader */ "./node_modules/react-hot-loader/index.js");
/* harmony import */ var react_hot_loader__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react_hot_loader__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");









var isOauthEnabled = function () {
    return !!app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].oauth && Object.keys(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].oauth).length > 0;
};
var LoginCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LoginCtrl, _super);
    function LoginCtrl(props) {
        var _this = _super.call(this, props) || this;
        _this.result = {};
        _this.changePassword = function (password) {
            var pw = {
                newPassword: password,
                confirmNew: password,
                oldPassword: 'admin',
            };
            Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_5__["getBackendSrv"])()
                .put('/api/user/password', pw)
                .then(function () {
                _this.toGrafana();
            })
                .catch(function (err) { return console.log(err); });
        };
        _this.login = function (formModel) {
            _this.setState({
                isLoggingIn: true,
            });
            Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_5__["getBackendSrv"])()
                .post('/login', formModel)
                .then(function (result) {
                _this.result = result;
                if (formModel.password !== 'admin' || app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].ldapEnabled || app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].authProxyEnabled) {
                    _this.toGrafana();
                    return;
                }
                else {
                    _this.changeView();
                }
            })
                .catch(function () {
                _this.setState({
                    isLoggingIn: false,
                });
            });
        };
        _this.changeView = function () {
            _this.setState({
                isChangingPassword: true,
            });
        };
        _this.toGrafana = function () {
            var params = _this.props.routeParams;
            // Use window.location.href to force page reload
            if (params.redirect && params.redirect[0] === '/') {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].appSubUrl + params.redirect;
            }
            else if (_this.result.redirectUrl) {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].appSubUrl + _this.result.redirectUrl;
            }
            else {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].appSubUrl + '/';
            }
        };
        _this.state = {
            isLoggingIn: false,
            isChangingPassword: false,
        };
        if (app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].loginError) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_7__["default"].emit('alert-warning', ['Login Failed', app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].loginError]);
        }
        return _this;
    }
    LoginCtrl.prototype.render = function () {
        var children = this.props.children;
        var _a = this.state, isLoggingIn = _a.isLoggingIn, isChangingPassword = _a.isChangingPassword;
        var _b = this, login = _b.login, toGrafana = _b.toGrafana, changePassword = _b.changePassword;
        var loginHint = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].loginHint, passwordHint = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].passwordHint, disableLoginForm = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].disableLoginForm, ldapEnabled = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].ldapEnabled, authProxyEnabled = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].authProxyEnabled, disableUserSignUp = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].disableUserSignUp;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, children({
            isOauthEnabled: isOauthEnabled(),
            loginHint: loginHint,
            passwordHint: passwordHint,
            disableLoginForm: disableLoginForm,
            ldapEnabled: ldapEnabled,
            authProxyEnabled: authProxyEnabled,
            disableUserSignUp: disableUserSignUp,
            login: login,
            isLoggingIn: isLoggingIn,
            changePassword: changePassword,
            skipPasswordChange: toGrafana,
            isChangingPassword: isChangingPassword,
        })));
    };
    return LoginCtrl;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var mapStateToProps = function (state) { return ({
    routeParams: state.location.routeParams,
}); };
var mapDispatchToProps = { updateLocation: app_core_actions__WEBPACK_IMPORTED_MODULE_3__["updateLocation"] };
/* harmony default export */ __webpack_exports__["default"] = (Object(react_hot_loader__WEBPACK_IMPORTED_MODULE_6__["hot"])(module)(Object(react_redux__WEBPACK_IMPORTED_MODULE_4__["connect"])(mapStateToProps, mapDispatchToProps)(LoginCtrl)));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../node_modules/webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module)))

/***/ }),

/***/ "./public/app/core/components/Login/LoginForm.tsx":
/*!********************************************************!*\
  !*** ./public/app/core/components/Login/LoginForm.tsx ***!
  \********************************************************/
/*! exports provided: LoginForm */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoginForm", function() { return LoginForm; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);


var LoginForm = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LoginForm, _super);
    function LoginForm(props) {
        var _this = _super.call(this, props) || this;
        _this.onSubmit = function (e) {
            e.preventDefault();
            var _a = _this.state, user = _a.user, password = _a.password, email = _a.email;
            if (_this.state.valid) {
                _this.props.onSubmit({ user: user, password: password, email: email });
            }
        };
        _this.onChangePassword = function (e) {
            _this.setState({
                password: e.target.value,
                valid: _this.validate(_this.state.user, e.target.value),
            });
        };
        _this.onChangeUsername = function (e) {
            _this.setState({
                user: e.target.value,
                valid: _this.validate(e.target.value, _this.state.password),
            });
        };
        _this.state = {
            user: '',
            password: '',
            email: '',
            valid: false,
        };
        return _this;
    }
    LoginForm.prototype.componentDidMount = function () {
        this.userInput.focus();
    };
    LoginForm.prototype.validate = function (user, password) {
        return user.length > 0 && password.length > 0;
    };
    LoginForm.prototype.render = function () {
        var _this = this;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", { name: "loginForm", className: "login-form-group gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", { ref: function (input) {
                        _this.userInput = input;
                    }, type: "text", name: "user", className: "gf-form-input login-form-input", required: true, placeholder: this.props.loginHint, "aria-label": "Username input field", onChange: this.onChangeUsername })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", { type: "password", name: "password", className: "gf-form-input login-form-input", required: true, "ng-model": "formModel.password", id: "inputPassword", placeholder: this.props.passwordHint, "aria-label": "Password input field", onChange: this.onChangePassword })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "login-button-group" },
                !this.props.isLoggingIn ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { type: "submit", "aria-label": "Login button", className: "btn btn-large p-x-2 " + (this.state.valid ? 'btn-primary' : 'btn-inverse'), onClick: this.onSubmit, disabled: !this.state.valid }, "Log In")) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { type: "submit", className: "btn btn-large p-x-2 btn-inverse btn-loading" },
                    "Logging In",
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, "."),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, "."),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, "."))),
                this.props.displayForgotPassword ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "small login-button-forgot-password" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: "user/password/send-reset-email" }, "Forgot your password?"))) : null)));
    };
    return LoginForm;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/core/components/Login/LoginPage.tsx":
/*!********************************************************!*\
  !*** ./public/app/core/components/Login/LoginPage.tsx ***!
  \********************************************************/
/*! exports provided: LoginPage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoginPage", function() { return LoginPage; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _UserSignup__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./UserSignup */ "./public/app/core/components/Login/UserSignup.tsx");
/* harmony import */ var _LoginServiceButtons__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./LoginServiceButtons */ "./public/app/core/components/Login/LoginServiceButtons.tsx");
/* harmony import */ var _LoginCtrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LoginCtrl */ "./public/app/core/components/Login/LoginCtrl.tsx");
/* harmony import */ var _LoginForm__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LoginForm */ "./public/app/core/components/Login/LoginForm.tsx");
/* harmony import */ var _ChangePassword__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ChangePassword */ "./public/app/core/components/Login/ChangePassword.tsx");
/* harmony import */ var react_transition_group__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! react-transition-group */ "./node_modules/react-transition-group/index.js");
/* harmony import */ var react_transition_group__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react_transition_group__WEBPACK_IMPORTED_MODULE_6__);







var LoginPage = function () {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login container" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-content" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-branding" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { className: "logo-icon", src: "public/img/grafana_icon.svg", alt: "Grafana" }),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "logo-wordmark" })),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LoginCtrl__WEBPACK_IMPORTED_MODULE_3__["default"], null, function (_a) {
                var loginHint = _a.loginHint, passwordHint = _a.passwordHint, isOauthEnabled = _a.isOauthEnabled, ldapEnabled = _a.ldapEnabled, authProxyEnabled = _a.authProxyEnabled, disableLoginForm = _a.disableLoginForm, disableUserSignUp = _a.disableUserSignUp, login = _a.login, isLoggingIn = _a.isLoggingIn, changePassword = _a.changePassword, skipPasswordChange = _a.skipPasswordChange, isChangingPassword = _a.isChangingPassword;
                return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-outer-box" },
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-inner-box " + (isChangingPassword ? 'hidden' : ''), id: "login-view" },
                        !disableLoginForm ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LoginForm__WEBPACK_IMPORTED_MODULE_4__["LoginForm"], { displayForgotPassword: !(ldapEnabled || authProxyEnabled), onSubmit: login, loginHint: loginHint, passwordHint: passwordHint, isLoggingIn: isLoggingIn })) : null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LoginServiceButtons__WEBPACK_IMPORTED_MODULE_2__["LoginServiceButtons"], null),
                        !disableUserSignUp ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_UserSignup__WEBPACK_IMPORTED_MODULE_1__["UserSignup"], null) : null),
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_transition_group__WEBPACK_IMPORTED_MODULE_6__["CSSTransition"], { appear: true, mountOnEnter: true, in: isChangingPassword, timeout: 250, classNames: "login-inner-box" },
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_ChangePassword__WEBPACK_IMPORTED_MODULE_5__["ChangePassword"], { onSubmit: changePassword, onSkip: skipPasswordChange, focus: isChangingPassword }))));
            }),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "clearfix" }))));
};


/***/ }),

/***/ "./public/app/core/components/Login/LoginServiceButtons.tsx":
/*!******************************************************************!*\
  !*** ./public/app/core/components/Login/LoginServiceButtons.tsx ***!
  \******************************************************************/
/*! exports provided: LoginServiceButtons */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoginServiceButtons", function() { return LoginServiceButtons; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");


var loginServices = function () { return ({
    saml: {
        enabled: app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].samlEnabled,
        name: 'SAML',
        className: 'github',
        icon: 'key',
    },
    google: {
        enabled: app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].oauth.google,
        name: 'Google',
    },
    github: {
        enabled: app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].oauth.github,
        name: 'GitHub',
    },
    gitlab: {
        enabled: app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].oauth.gitlab,
        name: 'GitLab',
    },
    grafanacom: {
        enabled: app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].oauth.grafana_com,
        name: 'Grafana.com',
        hrefName: 'grafana_com',
        icon: 'grafana_com',
    },
    oauth: {
        enabled: app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].oauth.generic_oauth,
        name: 'OAuth',
        icon: 'sign-in',
        hrefName: 'generic_oauth',
    },
}); };
var LoginDivider = function () {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "text-center login-divider" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-divider-line" })),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "login-divider-text" }, app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].disableLoginForm ? null : react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, "or"))),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-divider-line" }))),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "clearfix" })));
};
var LoginServiceButtons = function () {
    var keyNames = Object.keys(loginServices());
    var serviceElementsEnabled = keyNames.filter(function (key) {
        var service = loginServices()[key];
        return service.enabled;
    });
    if (serviceElementsEnabled.length === 0) {
        return null;
    }
    var serviceElements = serviceElementsEnabled.map(function (key) {
        var service = loginServices()[key];
        return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { key: key, className: "btn btn-medium btn-service btn-service--" + (service.className || key) + " login-btn", href: "login/" + (service.hrefName ? service.hrefName : key), target: "_self" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "btn-service-icon fa fa-" + (service.icon ? service.icon : key) }),
            "Sign in with ",
            service.name));
    });
    var divider = LoginDivider();
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
        divider,
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-oauth text-center" }, serviceElements)));
};


/***/ }),

/***/ "./public/app/core/components/Login/UserSignup.tsx":
/*!*********************************************************!*\
  !*** ./public/app/core/components/Login/UserSignup.tsx ***!
  \*********************************************************/
/*! exports provided: UserSignup */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserSignup", function() { return UserSignup; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var UserSignup = function () {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-signup-box" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "login-signup-title p-r-1" }, "New to Grafana?"),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: "signup", className: "btn btn-medium btn-signup btn-p-x-2" }, "Sign Up")));
};


/***/ }),

/***/ "./public/app/core/components/Page/Page.tsx":
/*!**************************************************!*\
  !*** ./public/app/core/components/Page/Page.tsx ***!
  \**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_selectors_navModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/selectors/navModel */ "./public/app/core/selectors/navModel.ts");
/* harmony import */ var _PageHeader_PageHeader__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../PageHeader/PageHeader */ "./public/app/core/components/PageHeader/PageHeader.tsx");
/* harmony import */ var _Footer_Footer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Footer/Footer */ "./public/app/core/components/Footer/Footer.tsx");
/* harmony import */ var _PageContents__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./PageContents */ "./public/app/core/components/Page/PageContents.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_8__);

// Libraries



// Components





var Page = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Page, _super);
    function Page() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.updateTitle = function () {
            var title = _this.getPageTitle;
            document.title = title ? title + ' - Grafana' : 'Grafana';
        };
        return _this;
    }
    Page.prototype.componentDidMount = function () {
        this.updateTitle();
    };
    Page.prototype.componentDidUpdate = function (prevProps) {
        if (!Object(lodash__WEBPACK_IMPORTED_MODULE_8__["isEqual"])(prevProps.navModel, this.props.navModel)) {
            this.updateTitle();
        }
    };
    Object.defineProperty(Page.prototype, "getPageTitle", {
        get: function () {
            var navModel = this.props.navModel;
            if (navModel) {
                return Object(app_core_selectors_navModel__WEBPACK_IMPORTED_MODULE_3__["getTitleFromNavModel"])(navModel) || undefined;
            }
            return undefined;
        },
        enumerable: true,
        configurable: true
    });
    Page.prototype.render = function () {
        var navModel = this.props.navModel;
        var buildInfo = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].buildInfo;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-scrollbar-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_7__["CustomScrollbar"], { autoHeightMin: '100%', className: "custom-scrollbar--page" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-scrollbar-content" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PageHeader_PageHeader__WEBPACK_IMPORTED_MODULE_4__["default"], { model: navModel }),
                    this.props.children,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Footer_Footer__WEBPACK_IMPORTED_MODULE_5__["default"], { appName: "Grafana", buildCommit: buildInfo.commit, buildVersion: buildInfo.version, newGrafanaVersion: buildInfo.latestVersion, newGrafanaVersionExists: buildInfo.hasUpdate })))));
    };
    Page.Header = _PageHeader_PageHeader__WEBPACK_IMPORTED_MODULE_4__["default"];
    Page.Contents = _PageContents__WEBPACK_IMPORTED_MODULE_6__["default"];
    return Page;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
/* harmony default export */ __webpack_exports__["default"] = (Page);


/***/ }),

/***/ "./public/app/core/components/Page/PageContents.tsx":
/*!**********************************************************!*\
  !*** ./public/app/core/components/Page/PageContents.tsx ***!
  \**********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _PageLoader_PageLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../PageLoader/PageLoader */ "./public/app/core/components/PageLoader/PageLoader.tsx");

// Libraries

// Components

var PageContents = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PageContents, _super);
    function PageContents() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PageContents.prototype.render = function () {
        var isLoading = this.props.isLoading;
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-container page-body" }, isLoading ? react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PageLoader_PageLoader__WEBPACK_IMPORTED_MODULE_2__["default"], null) : this.props.children);
    };
    return PageContents;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
/* harmony default export */ __webpack_exports__["default"] = (PageContents);


/***/ }),

/***/ "./public/app/core/components/PageHeader/PageHeader.tsx":
/*!**************************************************************!*\
  !*** ./public/app/core/components/PageHeader/PageHeader.tsx ***!
  \**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");




var SelectNav = function (_a) {
    var main = _a.main, customCss = _a.customCss;
    var defaultSelectedItem = main.children.find(function (navItem) {
        return navItem.active === true;
    });
    var gotoUrl = function (evt) {
        var element = evt.target;
        var url = element.options[element.selectedIndex].value;
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('location-change', { href: url });
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-wrapper width-20 " + customCss },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-select-icon " + defaultSelectedItem.icon, htmlFor: "page-header-select-nav" }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("select", { className: "gf-select-nav gf-form-input", value: defaultSelectedItem.url, onChange: gotoUrl, id: "page-header-select-nav" }, main.children.map(function (navItem) {
            if (navItem.hideFromTabs) {
                // TODO: Rename hideFromTabs => hideFromNav
                return null;
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("option", { key: navItem.url, value: navItem.url }, navItem.text));
        }))));
};
var Tabs = function (_a) {
    var main = _a.main, customCss = _a.customCss;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", { className: "gf-tabs " + customCss }, main.children.map(function (tab, idx) {
        if (tab.hideFromTabs) {
            return null;
        }
        var tabClasses = classnames__WEBPACK_IMPORTED_MODULE_2___default()({
            'gf-tabs-link': true,
            active: tab.active,
        });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: "gf-tabs-item", key: tab.url },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: tabClasses, target: tab.target, href: tab.url },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: tab.icon }),
                tab.text)));
    })));
};
var Navigation = function (_a) {
    var main = _a.main;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("nav", null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(SelectNav, { customCss: "page-header__select-nav", main: main }),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Tabs, { customCss: "page-header__tabs", main: main })));
};
var PageHeader = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PageHeader, _super);
    function PageHeader(props) {
        return _super.call(this, props) || this;
    }
    PageHeader.prototype.shouldComponentUpdate = function () {
        //Hack to re-render on changed props from angular with the @observer decorator
        return true;
    };
    PageHeader.prototype.renderTitle = function (title, breadcrumbs) {
        var e_1, _a;
        if (!title && (!breadcrumbs || breadcrumbs.length === 0)) {
            return null;
        }
        if (!breadcrumbs || breadcrumbs.length === 0) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h1", { className: "page-header__title" }, title);
        }
        var breadcrumbsResult = [];
        try {
            for (var breadcrumbs_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](breadcrumbs), breadcrumbs_1_1 = breadcrumbs_1.next(); !breadcrumbs_1_1.done; breadcrumbs_1_1 = breadcrumbs_1.next()) {
                var bc = breadcrumbs_1_1.value;
                if (bc.url) {
                    breadcrumbsResult.push(react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "text-link", key: breadcrumbsResult.length, href: bc.url }, bc.title));
                }
                else {
                    breadcrumbsResult.push(react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: breadcrumbsResult.length },
                        " / ",
                        bc.title));
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (breadcrumbs_1_1 && !breadcrumbs_1_1.done && (_a = breadcrumbs_1.return)) _a.call(breadcrumbs_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        breadcrumbsResult.push(react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: breadcrumbs.length + 1 },
            " / ",
            title));
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h1", { className: "page-header__title" }, breadcrumbsResult);
    };
    PageHeader.prototype.renderHeaderTitle = function (main) {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-header__inner" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "page-header__logo" },
                main.icon && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "page-header__icon " + main.icon }),
                main.img && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { className: "page-header__img", src: main.img })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-header__info-block" },
                this.renderTitle(main.text, main.breadcrumbs),
                main.subTitle && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-header__sub-title" }, main.subTitle))));
    };
    PageHeader.prototype.render = function () {
        var model = this.props.model;
        if (!model) {
            return null;
        }
        var main = model.main;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-header-canvas" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-container" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-header" },
                    this.renderHeaderTitle(main),
                    main.children && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Navigation, { main: main })))));
    };
    return PageHeader;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));
/* harmony default export */ __webpack_exports__["default"] = (PageHeader);


/***/ }),

/***/ "./public/app/core/components/PageLoader/PageLoader.tsx":
/*!**************************************************************!*\
  !*** ./public/app/core/components/PageLoader/PageLoader.tsx ***!
  \**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


var PageLoader = function (_a) {
    var _b = _a.pageName, pageName = _b === void 0 ? '' : _b;
    var loadingText = "Loading " + pageName + "...";
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "page-loader-wrapper" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["LoadingPlaceholder"], { text: loadingText })));
};
/* harmony default export */ __webpack_exports__["default"] = (PageLoader);


/***/ }),

/***/ "./public/app/core/components/PermissionList/AddPermission.tsx":
/*!*********************************************************************!*\
  !*** ./public/app/core/components/PermissionList/AddPermission.tsx ***!
  \*********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_components_Select_UserPicker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/components/Select/UserPicker */ "./public/app/core/components/Select/UserPicker.tsx");
/* harmony import */ var app_core_components_Select_TeamPicker__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/components/Select/TeamPicker */ "./public/app/core/components/Select/TeamPicker.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_types_acl__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/types/acl */ "./public/app/types/acl.ts");






var AddPermissions = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AddPermissions, _super);
    function AddPermissions(props) {
        var _this = _super.call(this, props) || this;
        _this.onTypeChanged = function (evt) {
            var type = evt.target.value;
            switch (type) {
                case app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].User:
                case app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].Team:
                    _this.setState({ type: type, userId: 0, teamId: 0, role: undefined });
                    break;
                case app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].Editor:
                    _this.setState({ type: type, userId: 0, teamId: 0, role: app_types_acl__WEBPACK_IMPORTED_MODULE_5__["OrgRole"].Editor });
                    break;
                case app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].Viewer:
                    _this.setState({ type: type, userId: 0, teamId: 0, role: app_types_acl__WEBPACK_IMPORTED_MODULE_5__["OrgRole"].Viewer });
                    break;
            }
        };
        _this.onUserSelected = function (user) {
            _this.setState({ userId: user && !Array.isArray(user) ? user.id : 0 });
        };
        _this.onTeamSelected = function (team) {
            _this.setState({ teamId: team && !Array.isArray(team) ? team.id : 0 });
        };
        _this.onPermissionChanged = function (permission) {
            _this.setState({ permission: permission.value });
        };
        _this.onSubmit = function (evt) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        evt.preventDefault();
                        return [4 /*yield*/, this.props.onAddPermission(this.state)];
                    case 1:
                        _a.sent();
                        this.setState(this.getCleanState());
                        return [2 /*return*/];
                }
            });
        }); };
        _this.state = _this.getCleanState();
        return _this;
    }
    AddPermissions.prototype.getCleanState = function () {
        return {
            userId: 0,
            teamId: 0,
            type: app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].Team,
            permission: app_types_acl__WEBPACK_IMPORTED_MODULE_5__["PermissionLevel"].View,
        };
    };
    AddPermissions.prototype.isValid = function () {
        switch (this.state.type) {
            case app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].Team:
                return this.state.teamId > 0;
            case app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].User:
                return this.state.userId > 0;
        }
        return true;
    };
    AddPermissions.prototype.render = function () {
        var onCancel = this.props.onCancel;
        var newItem = this.state;
        var pickerClassName = 'min-width-20';
        var isValid = this.isValid();
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline cta-form" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "cta-form__close btn btn-transparent", onClick: onCancel },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-close" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", { name: "addPermission", onSubmit: this.onSubmit },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", null, "Add Permission For"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-select-wrapper" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("select", { className: "gf-form-input gf-size-auto", value: newItem.type, onChange: this.onTypeChanged }, app_types_acl__WEBPACK_IMPORTED_MODULE_5__["dashboardAclTargets"].map(function (option, idx) {
                                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("option", { key: idx, value: option.value }, option.text));
                            })))),
                    newItem.type === app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].User ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Select_UserPicker__WEBPACK_IMPORTED_MODULE_2__["UserPicker"], { onSelected: this.onUserSelected, className: pickerClassName }))) : null,
                    newItem.type === app_types_acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"].Team ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Select_TeamPicker__WEBPACK_IMPORTED_MODULE_3__["TeamPicker"], { onSelected: this.onTeamSelected, className: pickerClassName }))) : null,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["Select"], { isSearchable: false, options: app_types_acl__WEBPACK_IMPORTED_MODULE_5__["dashboardPermissionLevels"], onChange: this.onPermissionChanged, className: "gf-form-select-box__control--menu-right" })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { "data-save-permission": true, className: "btn btn-primary", type: "submit", disabled: !isValid }, "Save"))))));
    };
    AddPermissions.defaultProps = {
        showPermissionLevels: true,
    };
    return AddPermissions;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
/* harmony default export */ __webpack_exports__["default"] = (AddPermissions);


/***/ }),

/***/ "./public/app/core/components/PermissionList/DisabledPermissionListItem.tsx":
/*!**********************************************************************************!*\
  !*** ./public/app/core/components/PermissionList/DisabledPermissionListItem.tsx ***!
  \**********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_types_acl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/types/acl */ "./public/app/types/acl.ts");




var DisabledPermissionListItem = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DisabledPermissionListItem, _super);
    function DisabledPermissionListItem() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DisabledPermissionListItem.prototype.render = function () {
        var item = this.props.item;
        var currentPermissionLevel = app_types_acl__WEBPACK_IMPORTED_MODULE_3__["dashboardPermissionLevels"].find(function (dp) { return dp.value === item.permission; });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { className: "gf-form-disabled" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { style: { width: '1%' } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { style: { width: '25px', height: '25px' }, className: "gicon gicon-shield" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { style: { width: '90%' } },
                item.name,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "filter-table__weak-italic" }, " (Role)")),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { className: "query-keyword" }, "Can"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { options: app_types_acl__WEBPACK_IMPORTED_MODULE_3__["dashboardPermissionLevels"], onChange: function () { }, isDisabled: true, className: "gf-form-select-box__control--menu-right", value: currentPermissionLevel }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn btn-inverse btn-small" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-lock" })))));
    };
    return DisabledPermissionListItem;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
/* harmony default export */ __webpack_exports__["default"] = (DisabledPermissionListItem);


/***/ }),

/***/ "./public/app/core/components/PermissionList/PermissionList.tsx":
/*!**********************************************************************!*\
  !*** ./public/app/core/components/PermissionList/PermissionList.tsx ***!
  \**********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _PermissionListItem__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./PermissionListItem */ "./public/app/core/components/PermissionList/PermissionListItem.tsx");
/* harmony import */ var _DisabledPermissionListItem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DisabledPermissionListItem */ "./public/app/core/components/PermissionList/DisabledPermissionListItem.tsx");




var PermissionList = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PermissionList, _super);
    function PermissionList() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PermissionList.prototype.render = function () {
        var _a = this.props, items = _a.items, onRemoveItem = _a.onRemoveItem, onPermissionChanged = _a.onPermissionChanged, isFetching = _a.isFetching, folderInfo = _a.folderInfo;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("table", { className: "filter-table gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tbody", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DisabledPermissionListItem__WEBPACK_IMPORTED_MODULE_3__["default"], { key: 0, item: {
                        name: 'Admin',
                        permission: 4,
                        icon: 'fa fa-fw fa-street-view',
                    } }),
                items.map(function (item, idx) {
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PermissionListItem__WEBPACK_IMPORTED_MODULE_2__["default"], { key: idx + 1, item: item, onRemoveItem: onRemoveItem, onPermissionChanged: onPermissionChanged, folderInfo: folderInfo }));
                }),
                isFetching === true && items.length < 1 ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { colSpan: 4 },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("em", null, "Loading permissions...")))) : null,
                isFetching === false && items.length < 1 ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { colSpan: 4 },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("em", null, "No permissions are set. Will only be accessible by admins.")))) : null)));
    };
    return PermissionList;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
/* harmony default export */ __webpack_exports__["default"] = (PermissionList);


/***/ }),

/***/ "./public/app/core/components/PermissionList/PermissionListItem.tsx":
/*!**************************************************************************!*\
  !*** ./public/app/core/components/PermissionList/PermissionListItem.tsx ***!
  \**************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_types_acl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/types/acl */ "./public/app/types/acl.ts");




var setClassNameHelper = function (inherited) {
    return inherited ? 'gf-form-disabled' : '';
};
function ItemAvatar(_a) {
    var item = _a.item;
    if (item.userAvatarUrl) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { className: "filter-table__avatar", src: item.userAvatarUrl });
    }
    if (item.teamAvatarUrl) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { className: "filter-table__avatar", src: item.teamAvatarUrl });
    }
    if (item.role === 'Editor') {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { style: { width: '25px', height: '25px' }, className: "gicon gicon-editor" });
    }
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { style: { width: '25px', height: '25px' }, className: "gicon gicon-viewer" });
}
function ItemDescription(_a) {
    var item = _a.item;
    if (item.userId) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "filter-table__weak-italic" }, "(User)");
    }
    if (item.teamId) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "filter-table__weak-italic" }, "(Team)");
    }
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "filter-table__weak-italic" }, "(Role)");
}
var PermissionsListItem = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PermissionsListItem, _super);
    function PermissionsListItem() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onPermissionChanged = function (option) {
            _this.props.onPermissionChanged(_this.props.item, option.value);
        };
        _this.onRemoveItem = function () {
            _this.props.onRemoveItem(_this.props.item);
        };
        return _this;
    }
    PermissionsListItem.prototype.render = function () {
        var _a = this.props, item = _a.item, folderInfo = _a.folderInfo;
        var inheritedFromRoot = item.dashboardId === -1 && !item.inherited;
        var currentPermissionLevel = app_types_acl__WEBPACK_IMPORTED_MODULE_3__["dashboardPermissionLevels"].find(function (dp) { return dp.value === item.permission; });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { className: setClassNameHelper(item.inherited) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { style: { width: '1%' } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ItemAvatar, { item: item })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { style: { width: '90%' } },
                item.name,
                " ",
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ItemDescription, { item: item })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null,
                item.inherited && folderInfo && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("em", { className: "muted no-wrap" },
                    "Inherited from folder",
                    ' ',
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "text-link", href: folderInfo.url + "/permissions" }, folderInfo.title),
                    ' ')),
                inheritedFromRoot && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("em", { className: "muted no-wrap" }, "Default Permission")),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { className: "query-keyword" }, "Can"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { isSearchable: false, options: app_types_acl__WEBPACK_IMPORTED_MODULE_3__["dashboardPermissionLevels"], onChange: this.onPermissionChanged, isDisabled: item.inherited, className: "gf-form-select-box__control--menu-right", value: currentPermissionLevel }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, !item.inherited ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "btn btn-danger btn-small", onClick: this.onRemoveItem },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-remove" }))) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn btn-inverse btn-small" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-lock" }))))));
    };
    return PermissionsListItem;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
/* harmony default export */ __webpack_exports__["default"] = (PermissionsListItem);


/***/ }),

/***/ "./public/app/core/components/PermissionList/PermissionsInfo.tsx":
/*!***********************************************************************!*\
  !*** ./public/app/core/components/PermissionList/PermissionsInfo.tsx ***!
  \***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

/* harmony default export */ __webpack_exports__["default"] = (function () {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h5", null, "What are Permissions?"),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "An Access Control List (ACL) model is used to limit access to Dashboard Folders. A user or a Team can be assigned permissions for a folder or for a single dashboard.")));
});


/***/ }),

/***/ "./public/app/core/components/SafeDynamicImport.tsx":
/*!**********************************************************!*\
  !*** ./public/app/core/components/SafeDynamicImport.tsx ***!
  \**********************************************************/
/*! exports provided: LoadingChunkPlaceHolder, SafeDynamicImport */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadingChunkPlaceHolder", function() { return LoadingChunkPlaceHolder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SafeDynamicImport", function() { return SafeDynamicImport; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var LoadingChunkPlaceHolder = function () { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])('preloader') },
    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["LoadingPlaceholder"], { text: 'Loading...' }))); };
function getAlertPageStyle() {
    return Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    width: 508px;\n    margin: 128px auto;\n  "], ["\n    width: 508px;\n    margin: 128px auto;\n  "])));
}
var SafeDynamicImport = function (importStatement) { return function (_a) {
    var props = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, []);
    var LazyComponent = Object(react__WEBPACK_IMPORTED_MODULE_1__["lazy"])(function () { return importStatement; });
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["ErrorBoundary"], null, function (_a) {
        var error = _a.error, errorInfo = _a.errorInfo;
        if (!errorInfo) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1__["Suspense"], { fallback: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LoadingChunkPlaceHolder, null) },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LazyComponent, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props))));
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: getAlertPageStyle() },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h2", null, "Unable to find application file"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h2", { className: "page-heading" }, "Grafana has likely been updated. Please try reloading the page."),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["Button"], { size: 'md', variant: 'secondary', icon: "fa fa-repeat", onClick: function () { return window.location.reload(); } }, "Reload")),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("details", { style: { whiteSpace: 'pre-wrap' } },
                error && error.toString(),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                errorInfo.componentStack)));
    }));
}; };
var templateObject_1;


/***/ }),

/***/ "./public/app/core/components/Select/MetricSelect.tsx":
/*!************************************************************!*\
  !*** ./public/app/core/components/Select/MetricSelect.tsx ***!
  \************************************************************/
/*! exports provided: MetricSelect */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetricSelect", function() { return MetricSelect; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var MetricSelect = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MetricSelect, _super);
    function MetricSelect(props) {
        var _this = _super.call(this, props) || this;
        _this.state = { options: [] };
        return _this;
    }
    MetricSelect.prototype.componentDidMount = function () {
        this.setState({ options: this.buildOptions(this.props) });
    };
    MetricSelect.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        if (nextProps.options.length > 0 || nextProps.variables.length) {
            this.setState({ options: this.buildOptions(nextProps) });
        }
    };
    MetricSelect.prototype.shouldComponentUpdate = function (nextProps) {
        var nextOptions = this.buildOptions(nextProps);
        return nextProps.value !== this.props.value || !lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isEqual(nextOptions, this.state.options);
    };
    MetricSelect.prototype.buildOptions = function (_a) {
        var _b = _a.variables, variables = _b === void 0 ? [] : _b, options = _a.options;
        return variables.length > 0 ? tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([this.getVariablesGroup()], options) : options;
    };
    MetricSelect.prototype.getVariablesGroup = function () {
        return {
            label: 'Template Variables',
            options: this.props.variables.map(function (v) { return ({
                label: "$" + v.name,
                value: "$" + v.name,
            }); }),
        };
    };
    MetricSelect.prototype.getSelectedOption = function () {
        var _this = this;
        var options = this.state.options;
        var allOptions = options.every(function (o) { return o.options; }) ? lodash__WEBPACK_IMPORTED_MODULE_2___default.a.flatten(options.map(function (o) { return o.options; })) : options;
        return allOptions.find(function (option) { return option.value === _this.props.value; });
    };
    MetricSelect.prototype.render = function () {
        var _a = this.props, placeholder = _a.placeholder, className = _a.className, isSearchable = _a.isSearchable, onChange = _a.onChange;
        var options = this.state.options;
        var selectedOption = this.getSelectedOption();
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["Select"], { className: className, isMulti: false, isClearable: false, backspaceRemovesValue: false, onChange: function (item) { return onChange(item.value); }, options: options, isSearchable: isSearchable, maxMenuHeight: 500, placeholder: placeholder, noOptionsMessage: function () { return 'No options found'; }, value: selectedOption }));
    };
    MetricSelect.defaultProps = {
        variables: [],
        options: [],
        isSearchable: true,
    };
    return MetricSelect;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/core/components/Select/TeamPicker.tsx":
/*!**********************************************************!*\
  !*** ./public/app/core/components/Select/TeamPicker.tsx ***!
  \**********************************************************/
/*! exports provided: TeamPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TeamPicker", function() { return TeamPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");






var TeamPicker = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TeamPicker, _super);
    function TeamPicker(props) {
        var _this = _super.call(this, props) || this;
        _this.state = { isLoading: false };
        _this.search = _this.search.bind(_this);
        _this.debouncedSearch = Object(lodash__WEBPACK_IMPORTED_MODULE_2__["debounce"])(_this.search, 300, {
            leading: true,
            trailing: true,
        });
        return _this;
    }
    TeamPicker.prototype.search = function (query) {
        var _this = this;
        var backendSrv = Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__["getBackendSrv"])();
        this.setState({ isLoading: true });
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNil(query)) {
            query = '';
        }
        return backendSrv.get("/api/teams/search?perpage=10&page=1&query=" + query).then(function (result) {
            var teams = result.teams.map(function (team) {
                return {
                    id: team.id,
                    value: team.id,
                    label: team.name,
                    name: team.name,
                    imgUrl: team.avatarUrl,
                };
            });
            _this.setState({ isLoading: false });
            return teams;
        });
    };
    TeamPicker.prototype.render = function () {
        var _a = this.props, onSelected = _a.onSelected, className = _a.className;
        var isLoading = this.state.isLoading;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "user-picker" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["AsyncSelect"], { isLoading: isLoading, defaultOptions: true, loadOptions: this.debouncedSearch, onChange: onSelected, className: className, placeholder: "Select a team", noOptionsMessage: function () { return 'No teams found'; } })));
    };
    return TeamPicker;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));



/***/ }),

/***/ "./public/app/core/components/Select/UserPicker.tsx":
/*!**********************************************************!*\
  !*** ./public/app/core/components/Select/UserPicker.tsx ***!
  \**********************************************************/
/*! exports provided: UserPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserPicker", function() { return UserPicker; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");

// Libraries


// Components

// Utils & Services


var UserPicker = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UserPicker, _super);
    function UserPicker(props) {
        var _this = _super.call(this, props) || this;
        _this.state = { isLoading: false };
        _this.search = _this.search.bind(_this);
        _this.debouncedSearch = Object(lodash__WEBPACK_IMPORTED_MODULE_2__["debounce"])(_this.search, 300, {
            leading: true,
            trailing: true,
        });
        return _this;
    }
    UserPicker.prototype.search = function (query) {
        var _this = this;
        var backendSrv = Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__["getBackendSrv"])();
        this.setState({ isLoading: true });
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNil(query)) {
            query = '';
        }
        return backendSrv
            .get("/api/org/users/lookup?query=" + query + "&limit=10")
            .then(function (result) {
            return result.map(function (user) { return ({
                id: user.userId,
                value: user.userId,
                label: user.login,
                imgUrl: user.avatarUrl,
                login: user.login,
            }); });
        })
            .finally(function () {
            _this.setState({ isLoading: false });
        });
    };
    UserPicker.prototype.render = function () {
        var _a = this.props, className = _a.className, onSelected = _a.onSelected;
        var isLoading = this.state.isLoading;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "user-picker" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["AsyncSelect"], { className: className, isLoading: isLoading, defaultOptions: true, loadOptions: this.debouncedSearch, onChange: onSelected, placeholder: "Select user", noOptionsMessage: function () { return 'No users found'; } })));
    };
    return UserPicker;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));



/***/ }),

/***/ "./public/app/core/components/SharedPreferences/SharedPreferences.tsx":
/*!****************************************************************************!*\
  !*** ./public/app/core/components/SharedPreferences/SharedPreferences.tsx ***!
  \****************************************************************************/
/*! exports provided: SharedPreferences, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SharedPreferences", function() { return SharedPreferences; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");




var themes = [{ value: '', label: 'Default' }, { value: 'dark', label: 'Dark' }, { value: 'light', label: 'Light' }];
var timezones = [
    { value: '', label: 'Default' },
    { value: 'browser', label: 'Local browser time' },
    { value: 'utc', label: 'UTC' },
];
var SharedPreferences = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SharedPreferences, _super);
    function SharedPreferences(props) {
        var _this = _super.call(this, props) || this;
        _this.backendSrv = Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__["getBackendSrv"])();
        _this.onSubmitForm = function (event) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var _a, homeDashboardId, theme, timezone;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
                switch (_b.label) {
                    case 0:
                        event.preventDefault();
                        _a = this.state, homeDashboardId = _a.homeDashboardId, theme = _a.theme, timezone = _a.timezone;
                        return [4 /*yield*/, this.backendSrv.put("/api/" + this.props.resourceUri + "/preferences", {
                                homeDashboardId: homeDashboardId,
                                theme: theme,
                                timezone: timezone,
                            })];
                    case 1:
                        _b.sent();
                        window.location.reload();
                        return [2 /*return*/];
                }
            });
        }); };
        _this.onThemeChanged = function (theme) {
            _this.setState({ theme: theme });
        };
        _this.onTimeZoneChanged = function (timezone) {
            _this.setState({ timezone: timezone });
        };
        _this.onHomeDashboardChanged = function (dashboardId) {
            _this.setState({ homeDashboardId: dashboardId });
        };
        _this.getFullDashName = function (dashboard) {
            if (typeof dashboard.folderTitle === 'undefined' || dashboard.folderTitle === '') {
                return dashboard.title;
            }
            return dashboard.folderTitle + ' / ' + dashboard.title;
        };
        _this.state = {
            homeDashboardId: 0,
            theme: '',
            timezone: '',
            dashboards: [],
        };
        return _this;
    }
    SharedPreferences.prototype.componentDidMount = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var prefs, dashboards, defaultDashboardHit, missing;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.backendSrv.get("/api/" + this.props.resourceUri + "/preferences")];
                    case 1:
                        prefs = _a.sent();
                        return [4 /*yield*/, this.backendSrv.search({ starred: true })];
                    case 2:
                        dashboards = _a.sent();
                        defaultDashboardHit = {
                            id: 0,
                            title: 'Default',
                            tags: [],
                            type: '',
                            uid: '',
                            uri: '',
                            url: '',
                            folderId: 0,
                            folderTitle: '',
                            folderUid: '',
                            folderUrl: '',
                            isStarred: false,
                            slug: '',
                        };
                        if (!(prefs.homeDashboardId > 0 && !dashboards.find(function (d) { return d.id === prefs.homeDashboardId; }))) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.backendSrv.search({ dashboardIds: [prefs.homeDashboardId] })];
                    case 3:
                        missing = _a.sent();
                        if (missing && missing.length > 0) {
                            dashboards.push(missing[0]);
                        }
                        _a.label = 4;
                    case 4:
                        this.setState({
                            homeDashboardId: prefs.homeDashboardId,
                            theme: prefs.theme,
                            timezone: prefs.timezone,
                            dashboards: tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([defaultDashboardHit], dashboards),
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    SharedPreferences.prototype.render = function () {
        var _this = this;
        var _a = this.state, theme = _a.theme, timezone = _a.timezone, homeDashboardId = _a.homeDashboardId, dashboards = _a.dashboards;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", { className: "section gf-form-group", onSubmit: this.onSubmitForm },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "page-heading" }, "Preferences"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label width-11" }, "UI Theme"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { isSearchable: false, value: themes.find(function (item) { return item.value === theme; }), options: themes, onChange: function (theme) { return _this.onThemeChanged(theme.value); }, width: 20 })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: 11, tooltip: "Not finding dashboard you want? Star it first, then it should appear in this select box." }, "Home Dashboard"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { value: dashboards.find(function (dashboard) { return dashboard.id === homeDashboardId; }), getOptionValue: function (i) { return i.id; }, getOptionLabel: this.getFullDashName, onChange: function (dashboard) { return _this.onHomeDashboardChanged(dashboard.id); }, options: dashboards, placeholder: "Choose default dashboard", width: 20 })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label width-11" }, "Timezone"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { isSearchable: false, value: timezones.find(function (item) { return item.value === timezone; }), onChange: function (timezone) { return _this.onTimeZoneChanged(timezone.value); }, options: timezones, width: 20 })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-button-row" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { type: "submit", className: "btn btn-primary" }, "Save"))));
    };
    return SharedPreferences;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (SharedPreferences);


/***/ }),

/***/ "./public/app/core/components/TagFilter/TagBadge.tsx":
/*!***********************************************************!*\
  !*** ./public/app/core/components/TagFilter/TagBadge.tsx ***!
  \***********************************************************/
/*! exports provided: TagBadge */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TagBadge", function() { return TagBadge; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_tags__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/tags */ "./public/app/core/utils/tags.ts");



var TagBadge = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TagBadge, _super);
    function TagBadge(props) {
        return _super.call(this, props) || this;
    }
    TagBadge.prototype.render = function () {
        var _a = this.props, label = _a.label, removeIcon = _a.removeIcon, count = _a.count;
        var _b = app_core_utils_tags__WEBPACK_IMPORTED_MODULE_2__["default"].getTagColorsFromName(label), color = _b.color, borderColor = _b.borderColor;
        var tagStyle = {
            backgroundColor: color,
            borderColor: borderColor,
        };
        var countLabel = count !== 0 && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "tag-count-label" }, "(" + count + ")");
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "label label-tag", style: tagStyle },
            removeIcon && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-remove" }),
            label,
            " ",
            countLabel));
    };
    return TagBadge;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/core/components/TagFilter/TagFilter.tsx":
/*!************************************************************!*\
  !*** ./public/app/core/components/TagFilter/TagFilter.tsx ***!
  \************************************************************/
/*! exports provided: TagFilter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TagFilter", function() { return TagFilter; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @torkelo/react-select */ "./node_modules/@torkelo/react-select/dist/react-select.esm.js");
/* harmony import */ var _torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @torkelo/react-select/lib/Async */ "./node_modules/@torkelo/react-select/lib/Async.js");
/* harmony import */ var _torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _TagOption__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./TagOption */ "./public/app/core/components/TagFilter/TagOption.tsx");
/* harmony import */ var _TagBadge__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./TagBadge */ "./public/app/core/components/TagFilter/TagBadge.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _FilterInput_FilterInput__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../FilterInput/FilterInput */ "./public/app/core/components/FilterInput/FilterInput.tsx");

// Libraries

// @ts-ignore

// @ts-ignore

// Components




var TagFilter = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TagFilter, _super);
    function TagFilter(props) {
        var _this = _super.call(this, props) || this;
        _this.onLoadOptions = function (query) {
            return _this.props.tagOptions().then(function (options) {
                return options.map(function (option) { return ({
                    value: option.term,
                    label: option.term,
                    count: option.count,
                }); });
            });
        };
        _this.onChange = function (newTags) {
            _this.props.onChange(newTags.map(function (tag) { return tag.value; }));
        };
        return _this;
    }
    TagFilter.prototype.render = function () {
        var tags = this.props.tags.map(function (tag) { return ({ value: tag, label: tag, count: 0 }); });
        var selectOptions = {
            classNamePrefix: 'gf-form-select-box',
            isMulti: true,
            defaultOptions: true,
            loadOptions: this.onLoadOptions,
            onChange: this.onChange,
            className: 'gf-form-input gf-form-input--form-dropdown',
            placeholder: 'Tags',
            loadingMessage: function () { return 'Loading...'; },
            noOptionsMessage: function () { return 'No tags found'; },
            getOptionValue: function (i) { return i.value; },
            getOptionLabel: function (i) { return i.label; },
            value: tags,
            styles: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["resetSelectStyles"])(),
            filterOption: function (option, searchQuery) {
                var regex = RegExp(Object(_FilterInput_FilterInput__WEBPACK_IMPORTED_MODULE_7__["escapeStringForRegex"])(searchQuery), 'i');
                return regex.test(option.value);
            },
            components: {
                Option: _TagOption__WEBPACK_IMPORTED_MODULE_4__["TagOption"],
                IndicatorsContainer: _grafana_ui__WEBPACK_IMPORTED_MODULE_6__["IndicatorsContainer"],
                NoOptionsMessage: _grafana_ui__WEBPACK_IMPORTED_MODULE_6__["NoOptionsMessage"],
                MultiValueLabel: function () {
                    return null; // We want the whole tag to be clickable so we use MultiValueRemove instead
                },
                MultiValueRemove: function (props) {
                    var data = props.data;
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__["components"].MultiValueRemove, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TagBadge__WEBPACK_IMPORTED_MODULE_5__["TagBadge"], { key: data.label, label: data.label, removeIcon: true, count: data.count })));
                },
            },
        };
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--has-input-icon gf-form--grow" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "tag-filter" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select_lib_Async__WEBPACK_IMPORTED_MODULE_3___default.a, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, selectOptions))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "gf-form-input-icon fa fa-tag" })));
    };
    return TagFilter;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/core/components/TagFilter/TagOption.tsx":
/*!************************************************************!*\
  !*** ./public/app/core/components/TagFilter/TagOption.tsx ***!
  \************************************************************/
/*! exports provided: TagOption, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TagOption", function() { return TagOption; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @torkelo/react-select */ "./node_modules/@torkelo/react-select/dist/react-select.esm.js");
/* harmony import */ var _TagBadge__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./TagBadge */ "./public/app/core/components/TagFilter/TagBadge.tsx");

// Libraries

// @ts-ignore


var TagOption = function (props) {
    var data = props.data, className = props.className, label = props.label;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_torkelo_react_select__WEBPACK_IMPORTED_MODULE_2__["components"].Option, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "tag-filter-option btn btn-link " + (className || '') },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TagBadge__WEBPACK_IMPORTED_MODULE_3__["TagBadge"], { label: label, removeIcon: false, count: data.count }))));
};
/* harmony default export */ __webpack_exports__["default"] = (TagOption);


/***/ }),

/***/ "./public/app/core/components/code_editor/code_editor.ts":
/*!***************************************************************!*\
  !*** ./public/app/core/components/code_editor/code_editor.ts ***!
  \***************************************************************/
/*! exports provided: codeEditorDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "codeEditorDirective", function() { return codeEditorDirective; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/**
 * codeEditor directive based on Ace code editor
 * https://github.com/ajaxorg/ace
 *
 * Basic usage:
 * <code-editor content="ctrl.target.query" on-change="ctrl.panelCtrl.refresh()"
 *  data-mode="sql" data-show-gutter>
 * </code-editor>
 *
 * Params:
 * content:      Editor content.
 * onChange:     Function called on content change (invoked on editor blur, ctrl+enter, not on every change).
 * getCompleter: Function returned external completer. Completer is an object implemented getCompletions() method,
 *               see Prometheus Data Source implementation for details.
 *
 * Some Ace editor options available via data-* attributes:
 * data-mode               - Language mode (text, sql, javascript, etc.). Default is 'text'.
 * data-theme              - Editor theme (eg 'solarized_dark').
 * data-max-lines          - Max editor height in lines. Editor grows automatically from 1 to maxLines.
 * data-show-gutter        - Show gutter (contains line numbers and additional info).
 * data-tab-size           - Tab size, default is 2.
 * data-behaviours-enabled - Specifies whether to use behaviors or not. "Behaviors" in this case is the auto-pairing of
 *                           special characters, like quotation marks, parenthesis, or brackets.
 * data-snippets-enabled   - Specifies whether to use snippets or not. "Snippets" are small pieces of code that can be
 *                           inserted via the completion box.
 *
 * Keybindings:
 * Ctrl-Enter (Command-Enter): run onChange() function
 */



var DEFAULT_THEME_DARK = 'ace/theme/grafana-dark';
var DEFAULT_THEME_LIGHT = 'ace/theme/textmate';
var DEFAULT_MODE = 'text';
var DEFAULT_MAX_LINES = 10;
var DEFAULT_TAB_SIZE = 2;
var DEFAULT_BEHAVIORS = true;
var DEFAULT_SNIPPETS = true;
var editorTemplate = "<div></div>";
function link(scope, elem, attrs) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
        function setLangMode(lang) {
            ace.acequire('ace/ext/language_tools');
            codeEditor.setOptions({
                enableBasicAutocompletion: true,
                enableLiveAutocompletion: true,
                enableSnippets: snippetsEnabled,
            });
            if (scope.getCompleter()) {
                // make copy of array as ace seems to share completers array between instances
                var anyEditor = codeEditor;
                anyEditor.completers = anyEditor.completers.slice();
                anyEditor.completers.push(scope.getCompleter());
            }
            var aceModeName = "ace/mode/" + lang;
            editorSession.setMode(aceModeName);
        }
        function setThemeMode() {
            var theme = DEFAULT_THEME_DARK;
            if (app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].bootData.user.lightTheme) {
                theme = DEFAULT_THEME_LIGHT;
            }
            codeEditor.setTheme(theme);
        }
        function setEditorContent(value) {
            codeEditor.setValue(value);
            codeEditor.clearSelection();
        }
        var langMode, maxLines, showGutter, tabSize, behavioursEnabled, snippetsEnabled, aceElem, ace, codeEditor, editorSession, editorOptions, textarea;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    langMode = attrs.mode || DEFAULT_MODE;
                    maxLines = attrs.maxLines || DEFAULT_MAX_LINES;
                    showGutter = attrs.showGutter !== undefined;
                    tabSize = attrs.tabSize || DEFAULT_TAB_SIZE;
                    behavioursEnabled = attrs.behavioursEnabled ? attrs.behavioursEnabled === 'true' : DEFAULT_BEHAVIORS;
                    snippetsEnabled = attrs.snippetsEnabled ? attrs.snippetsEnabled === 'true' : DEFAULT_SNIPPETS;
                    aceElem = elem.get(0);
                    return [4 /*yield*/, __webpack_require__.e(/*! import() | brace */ "brace").then(__webpack_require__.t.bind(null, /*! brace */ "./node_modules/brace/index.js", 7))];
                case 1:
                    ace = (_a.sent()).default;
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 4).then(__webpack_require__.t.bind(null, /*! brace/ext/language_tools */ "./node_modules/brace/ext/language_tools.js", 7))];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 13).then(__webpack_require__.t.bind(null, /*! brace/theme/textmate */ "./node_modules/brace/theme/textmate.js", 7))];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 7).then(__webpack_require__.t.bind(null, /*! brace/mode/text */ "./node_modules/brace/mode/text.js", 7))];
                case 4:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 12).then(__webpack_require__.t.bind(null, /*! brace/snippets/text */ "./node_modules/brace/snippets/text.js", 7))];
                case 5:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 5).then(__webpack_require__.t.bind(null, /*! brace/mode/sql */ "./node_modules/brace/mode/sql.js", 7))];
                case 6:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 10).then(__webpack_require__.t.bind(null, /*! brace/snippets/sql */ "./node_modules/brace/snippets/sql.js", 7))];
                case 7:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 6).then(__webpack_require__.t.bind(null, /*! brace/mode/sqlserver */ "./node_modules/brace/mode/sqlserver.js", 7))];
                case 8:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 11).then(__webpack_require__.t.bind(null, /*! brace/snippets/sqlserver */ "./node_modules/brace/snippets/sqlserver.js", 7))];
                case 9:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 0).then(__webpack_require__.t.bind(null, /*! brace/mode/markdown */ "./node_modules/brace/mode/markdown.js", 7))];
                case 10:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 9).then(__webpack_require__.t.bind(null, /*! brace/snippets/markdown */ "./node_modules/brace/snippets/markdown.js", 7))];
                case 11:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 2).then(__webpack_require__.t.bind(null, /*! brace/mode/json */ "./node_modules/brace/mode/json.js", 7))];
                case 12:
                    _a.sent();
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 8).then(__webpack_require__.t.bind(null, /*! brace/snippets/json */ "./node_modules/brace/snippets/json.js", 7))];
                case 13:
                    _a.sent();
                    // @ts-ignore
                    return [4 /*yield*/, __webpack_require__.e(/*! import() */ 14).then(__webpack_require__.t.bind(null, /*! ./theme-grafana-dark */ "./public/app/core/components/code_editor/theme-grafana-dark.js", 7))];
                case 14:
                    // @ts-ignore
                    _a.sent();
                    codeEditor = ace.edit(aceElem);
                    editorSession = codeEditor.getSession();
                    editorOptions = {
                        maxLines: maxLines,
                        showGutter: showGutter,
                        tabSize: tabSize,
                        behavioursEnabled: behavioursEnabled,
                        highlightActiveLine: false,
                        showPrintMargin: false,
                        autoScrollEditorIntoView: true,
                    };
                    // Set options
                    codeEditor.setOptions(editorOptions);
                    // disable depreacation warning
                    codeEditor.$blockScrolling = Infinity;
                    // Padding hacks
                    codeEditor.renderer.setScrollMargin(10, 10);
                    codeEditor.renderer.setPadding(10);
                    setThemeMode();
                    setLangMode(langMode);
                    setEditorContent(scope.content);
                    // Add classes
                    elem.addClass('gf-code-editor');
                    textarea = elem.find('textarea');
                    textarea.addClass('gf-form-input');
                    if (scope.codeEditorFocus) {
                        setTimeout(function () {
                            textarea.focus();
                            var domEl = textarea[0];
                            if (domEl.setSelectionRange) {
                                var pos = textarea.val().length * 2;
                                domEl.setSelectionRange(pos, pos);
                            }
                        }, 100);
                    }
                    // Event handlers
                    editorSession.on('change', function (e) {
                        scope.$apply(function () {
                            var newValue = codeEditor.getValue();
                            scope.content = newValue;
                        });
                    });
                    // Sync with outer scope - update editor content if model has been changed from outside of directive.
                    scope.$watch('content', function (newValue, oldValue) {
                        var editorValue = codeEditor.getValue();
                        if (newValue !== editorValue && newValue !== oldValue) {
                            scope.$$postDigest(function () {
                                setEditorContent(newValue);
                            });
                        }
                    });
                    codeEditor.on('blur', function () {
                        scope.onChange();
                    });
                    scope.$on('$destroy', function () {
                        codeEditor.destroy();
                    });
                    // Keybindings
                    codeEditor.commands.addCommand({
                        name: 'executeQuery',
                        bindKey: { win: 'Ctrl-Enter', mac: 'Command-Enter' },
                        exec: function () {
                            scope.onChange();
                        },
                    });
                    return [2 /*return*/];
            }
        });
    });
}
function codeEditorDirective() {
    return {
        restrict: 'E',
        template: editorTemplate,
        scope: {
            content: '=',
            datasource: '=',
            codeEditorFocus: '<',
            onChange: '&',
            getCompleter: '&',
        },
        link: link,
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('codeEditor', codeEditorDirective);


/***/ }),

/***/ "./public/app/core/components/colorpicker/spectrum_picker.ts":
/*!*******************************************************************!*\
  !*** ./public/app/core/components/colorpicker/spectrum_picker.ts ***!
  \*******************************************************************/
/*! exports provided: spectrumPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spectrumPicker", function() { return spectrumPicker; });
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../core_module */ "./public/app/core/core_module.ts");
/**
 * Wrapper for the new ngReact <color-picker> directive for backward compatibility.
 * Allows remaining <spectrum-picker> untouched in outdated plugins.
 * Technically, it's just a wrapper for react component with two-way data binding support.
 */

/** @ngInject */
function spectrumPicker() {
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: true,
        replace: true,
        template: '<color-picker color="ngModel.$viewValue" onChange="onColorChange"></color-picker>',
        link: function (scope, element, attrs, ngModel) {
            scope.ngModel = ngModel;
            scope.onColorChange = function (color) {
                ngModel.$setViewValue(color);
            };
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('spectrumPicker', spectrumPicker);


/***/ }),

/***/ "./public/app/core/components/dashboard_selector.ts":
/*!**********************************************************!*\
  !*** ./public/app/core/components/dashboard_selector.ts ***!
  \**********************************************************/
/*! exports provided: DashboardSelectorCtrl, dashboardSelector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardSelectorCtrl", function() { return DashboardSelectorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardSelector", function() { return dashboardSelector; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var template = "\n<select class=\"gf-form-input\" ng-model=\"ctrl.model\" ng-options=\"f.value as f.text for f in ctrl.options\"></select>\n";
var DashboardSelectorCtrl = /** @class */ (function () {
    /** @ngInject */
    function DashboardSelectorCtrl(backendSrv) {
        this.backendSrv = backendSrv;
    }
    DashboardSelectorCtrl.prototype.$onInit = function () {
        var _this = this;
        this.options = [{ value: 0, text: 'Default' }];
        return this.backendSrv.search({ starred: true }).then(function (res) {
            res.forEach(function (dash) {
                _this.options.push({ value: dash.id, text: dash.title });
            });
        });
    };
    return DashboardSelectorCtrl;
}());

function dashboardSelector() {
    return {
        restrict: 'E',
        controller: DashboardSelectorCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        template: template,
        scope: {
            model: '=',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('dashboardSelector', dashboardSelector);


/***/ }),

/***/ "./public/app/core/components/form_dropdown/form_dropdown.ts":
/*!*******************************************************************!*\
  !*** ./public/app/core/components/form_dropdown/form_dropdown.ts ***!
  \*******************************************************************/
/*! exports provided: FormDropdownCtrl, formDropdownDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormDropdownCtrl", function() { return FormDropdownCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formDropdownDirective", function() { return formDropdownDirective; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../core_module */ "./public/app/core/core_module.ts");


function typeaheadMatcher(item) {
    var str = this.query;
    if (str === '') {
        return true;
    }
    if (str[0] === '/') {
        str = str.substring(1);
    }
    if (str[str.length - 1] === '/') {
        str = str.substring(0, str.length - 1);
    }
    return item.toLowerCase().match(str.toLowerCase());
}
var FormDropdownCtrl = /** @class */ (function () {
    /** @ngInject */
    function FormDropdownCtrl($scope, $element, $sce, templateSrv, $q) {
        var _this = this;
        this.$scope = $scope;
        this.$sce = $sce;
        this.templateSrv = templateSrv;
        this.$q = $q;
        this.inputElement = $element.find('input').first();
        this.linkElement = $element.find('a').first();
        this.linkMode = true;
        this.cancelBlur = null;
        // listen to model changes
        $scope.$watch('ctrl.model', this.modelChanged.bind(this));
        if (this.labelMode) {
            this.cssClasses = 'gf-form-label ' + this.cssClass;
        }
        else {
            this.cssClasses = 'gf-form-input gf-form-input--dropdown ' + this.cssClass;
        }
        if (this.placeholder) {
            this.inputElement.attr('placeholder', this.placeholder);
        }
        this.inputElement.attr('data-provide', 'typeahead');
        this.inputElement.typeahead({
            source: this.typeaheadSource.bind(this),
            minLength: 0,
            items: 10000,
            updater: this.typeaheadUpdater.bind(this),
            matcher: typeaheadMatcher,
        });
        // modify typeahead lookup
        // this = typeahead
        var typeahead = this.inputElement.data('typeahead');
        typeahead.lookup = function () {
            this.query = this.$element.val() || '';
            this.source(this.query, this.process.bind(this));
        };
        if (this.debounce) {
            typeahead.lookup = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.debounce(typeahead.lookup, 500, { leading: true });
        }
        this.linkElement.keydown(function (evt) {
            // trigger typeahead on down arrow or enter key
            if (evt.keyCode === 40 || evt.keyCode === 13) {
                _this.linkElement.click();
            }
        });
        this.inputElement.keydown(function (evt) {
            if (evt.keyCode === 13) {
                setTimeout(function () {
                    _this.inputElement.blur();
                }, 300);
            }
        });
        this.inputElement.blur(this.inputBlur.bind(this));
        if (this.startOpen) {
            setTimeout(this.open.bind(this), 0);
        }
    }
    FormDropdownCtrl.prototype.getOptionsInternal = function (query) {
        var result = this.getOptions({ $query: query });
        if (this.isPromiseLike(result)) {
            return result;
        }
        return this.$q.when(result);
    };
    FormDropdownCtrl.prototype.isPromiseLike = function (obj) {
        return obj && typeof obj.then === 'function';
    };
    FormDropdownCtrl.prototype.modelChanged = function () {
        var _this = this;
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isObject(this.model)) {
            this.updateDisplay(this.model.text);
        }
        else {
            // if we have text use it
            if (this.lookupText) {
                this.getOptionsInternal('').then(function (options) {
                    var item = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(options, { value: _this.model });
                    _this.updateDisplay(item ? item.text : _this.model);
                });
            }
            else {
                this.updateDisplay(this.model);
            }
        }
    };
    FormDropdownCtrl.prototype.typeaheadSource = function (query, callback) {
        var _this = this;
        this.getOptionsInternal(query).then(function (options) {
            _this.optionCache = options;
            // extract texts
            var optionTexts = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(options, function (op) {
                return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(op.text);
            });
            // add custom values
            if (_this.allowCustom && _this.text !== '') {
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.indexOf(optionTexts, _this.text) === -1) {
                    optionTexts.unshift(_this.text);
                }
            }
            callback(optionTexts);
        });
    };
    FormDropdownCtrl.prototype.typeaheadUpdater = function (text) {
        if (text === this.text) {
            clearTimeout(this.cancelBlur);
            this.inputElement.focus();
            return text;
        }
        this.inputElement.val(text);
        this.switchToLink(true);
        return text;
    };
    FormDropdownCtrl.prototype.switchToLink = function (fromClick) {
        if (this.linkMode && !fromClick) {
            return;
        }
        clearTimeout(this.cancelBlur);
        this.cancelBlur = null;
        this.linkMode = true;
        this.inputElement.hide();
        this.linkElement.show();
        this.updateValue(this.inputElement.val());
    };
    FormDropdownCtrl.prototype.inputBlur = function () {
        // happens long before the click event on the typeahead options
        // need to have long delay because the blur
        this.cancelBlur = setTimeout(this.switchToLink.bind(this), 200);
    };
    FormDropdownCtrl.prototype.updateValue = function (text) {
        var _this = this;
        text = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.unescape(text);
        if (text === '' || this.text === text) {
            return;
        }
        this.$scope.$apply(function () {
            var option = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(_this.optionCache, { text: text });
            if (option) {
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isObject(_this.model)) {
                    _this.model = option;
                }
                else {
                    _this.model = option.value;
                }
                _this.text = option.text;
            }
            else if (_this.allowCustom) {
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isObject(_this.model)) {
                    _this.model.text = _this.model.value = text;
                }
                else {
                    _this.model = text;
                }
                _this.text = text;
            }
            // needs to call this after digest so
            // property is synced with outerscope
            _this.$scope.$$postDigest(function () {
                _this.$scope.$apply(function () {
                    _this.onChange({ $option: option });
                });
            });
        });
    };
    FormDropdownCtrl.prototype.updateDisplay = function (text) {
        this.text = text;
        this.display = this.$sce.trustAsHtml(this.templateSrv.highlightVariablesAsHtml(text));
    };
    FormDropdownCtrl.prototype.open = function () {
        this.inputElement.css('width', Math.max(this.linkElement.width(), 80) + 16 + 'px');
        this.inputElement.show();
        this.inputElement.focus();
        this.linkElement.hide();
        this.linkMode = false;
        var typeahead = this.inputElement.data('typeahead');
        if (typeahead) {
            this.inputElement.val('');
            typeahead.lookup();
        }
    };
    return FormDropdownCtrl;
}());

var template = "\n<input type=\"text\"\n  data-provide=\"typeahead\"\n  class=\"gf-form-input\"\n  spellcheck=\"false\"\n  style=\"display:none\">\n</input>\n<a ng-class=\"ctrl.cssClasses\"\n   tabindex=\"1\"\n   ng-click=\"ctrl.open()\"\n   give-focus=\"ctrl.focus\"\n   ng-bind-html=\"ctrl.display || '&nbsp;'\">\n</a>\n";
function formDropdownDirective() {
    return {
        restrict: 'E',
        template: template,
        controller: FormDropdownCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            model: '=',
            getOptions: '&',
            onChange: '&',
            cssClass: '@',
            allowCustom: '@',
            labelMode: '@',
            lookupText: '@',
            placeholder: '@',
            startOpen: '@',
            debounce: '@',
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('gfFormDropdown', formDropdownDirective);


/***/ }),

/***/ "./public/app/core/components/help/help.ts":
/*!*************************************************!*\
  !*** ./public/app/core/components/help/help.ts ***!
  \*************************************************/
/*! exports provided: HelpCtrl, helpModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HelpCtrl", function() { return HelpCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "helpModal", function() { return helpModal; });
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");


var HelpCtrl = /** @class */ (function () {
    /** @ngInject */
    function HelpCtrl() {
        this.tabIndex = 0;
        this.shortcuts = {
            Global: [
                { keys: ['g', 'h'], description: 'Go to Home Dashboard' },
                { keys: ['g', 'p'], description: 'Go to Profile' },
                { keys: ['s', 'o'], description: 'Open search' },
                { keys: ['esc'], description: 'Exit edit/setting views' },
            ],
            Dashboard: [
                { keys: ['mod+s'], description: 'Save dashboard' },
                { keys: ['d', 'r'], description: 'Refresh all panels' },
                { keys: ['d', 's'], description: 'Dashboard settings' },
                { keys: ['d', 'v'], description: 'Toggle in-active / view mode' },
                { keys: ['d', 'k'], description: 'Toggle kiosk mode (hides top nav)' },
                { keys: ['d', 'E'], description: 'Expand all rows' },
                { keys: ['d', 'C'], description: 'Collapse all rows' },
                { keys: ['d', 'a'], description: 'Toggle auto fit panels (experimental feature)' },
                { keys: ['mod+o'], description: 'Toggle shared graph crosshair' },
                { keys: ['d', 'l'], description: 'Toggle all panel legends' },
            ],
            'Focused Panel': [
                { keys: ['e'], description: 'Toggle panel edit view' },
                { keys: ['v'], description: 'Toggle panel fullscreen view' },
                { keys: ['p', 's'], description: 'Open Panel Share Modal' },
                { keys: ['p', 'd'], description: 'Duplicate Panel' },
                { keys: ['p', 'r'], description: 'Remove Panel' },
                { keys: ['p', 'l'], description: 'Toggle panel legend' },
            ],
            'Time Range': [
                { keys: ['t', 'z'], description: 'Zoom out time range' },
                {
                    keys: ['t', '<i class="fa fa-long-arrow-left"></i>'],
                    description: 'Move time range back',
                },
                {
                    keys: ['t', '<i class="fa fa-long-arrow-right"></i>'],
                    description: 'Move time range forward',
                },
            ],
        };
    }
    HelpCtrl.prototype.dismiss = function () {
        app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].emit('hide-modal');
    };
    return HelpCtrl;
}());

function helpModal() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/core/components/help/help.html',
        controller: HelpCtrl,
        bindToController: true,
        transclude: true,
        controllerAs: 'ctrl',
        scope: {},
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('helpModal', helpModal);


/***/ }),

/***/ "./public/app/core/components/info_popover.ts":
/*!****************************************************!*\
  !*** ./public/app/core/components/info_popover.ts ***!
  \****************************************************/
/*! exports provided: infoPopover */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "infoPopover", function() { return infoPopover; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tether-drop */ "./node_modules/tether-drop/dist/js/drop.js");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tether_drop__WEBPACK_IMPORTED_MODULE_2__);


// @ts-ignore

function infoPopover() {
    return {
        restrict: 'E',
        template: '<i class="fa fa-info-circle"></i>',
        transclude: true,
        link: function (scope, elem, attrs, ctrl, transclude) {
            var offset = attrs.offset || '0 -10px';
            var position = attrs.position || 'right middle';
            var classes = 'drop-help drop-hide-out-of-bounds';
            var openOn = 'hover';
            elem.addClass('gf-form-help-icon');
            if (attrs.wide) {
                classes += ' drop-wide';
            }
            if (attrs.mode) {
                elem.addClass('gf-form-help-icon--' + attrs.mode);
            }
            transclude(function (clone, newScope) {
                var content = document.createElement('div');
                content.className = 'markdown-html';
                lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(clone, function (node) {
                    content.appendChild(node);
                });
                var dropOptions = {
                    target: elem[0],
                    content: content,
                    position: position,
                    classes: classes,
                    openOn: openOn,
                    hoverOpenDelay: 400,
                    tetherOptions: {
                        offset: offset,
                        constraints: [
                            {
                                to: 'window',
                                attachment: 'together',
                                pin: true,
                            },
                        ],
                    },
                };
                // Create drop in next digest after directive content is rendered.
                scope.$applyAsync(function () {
                    var drop = new tether_drop__WEBPACK_IMPORTED_MODULE_2___default.a(dropOptions);
                    var unbind = scope.$on('$destroy', function () {
                        drop.destroy();
                        unbind();
                    });
                });
            });
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('infoPopover', infoPopover);


/***/ }),

/***/ "./public/app/core/components/jsontree/jsontree.ts":
/*!*********************************************************!*\
  !*** ./public/app/core/components/jsontree/jsontree.ts ***!
  \*********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('jsonTree', [
    function jsonTreeDirective() {
        return {
            restrict: 'E',
            scope: {
                object: '=',
                startExpanded: '@',
                rootName: '@',
            },
            link: function (scope, elem) {
                var _a;
                var expansionLevel = scope.startExpanded;
                if (scope.startExpanded === 'true') {
                    expansionLevel = 2;
                }
                else if (scope.startExpanded === 'false') {
                    expansionLevel = 1;
                }
                var jsonObject = (_a = {}, _a[scope.rootName] = scope.object, _a);
                var jsonExp = new _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["JsonExplorer"](jsonObject, expansionLevel, {
                    animateOpen: true,
                });
                var html = jsonExp.render(true);
                elem.append(html);
            },
        };
    },
]);


/***/ }),

/***/ "./public/app/core/components/layout_selector/layout_selector.ts":
/*!***********************************************************************!*\
  !*** ./public/app/core/components/layout_selector/layout_selector.ts ***!
  \***********************************************************************/
/*! exports provided: LayoutSelectorCtrl, layoutSelector, layoutMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LayoutSelectorCtrl", function() { return LayoutSelectorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "layoutSelector", function() { return layoutSelector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "layoutMode", function() { return layoutMode; });
/* harmony import */ var app_core_store__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/store */ "./public/app/core/store.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");


var template = "\n<div class=\"layout-selector\">\n  <button ng-click=\"ctrl.listView()\" ng-class=\"{active: ctrl.mode === 'list'}\">\n    <i class=\"fa fa-list\"></i>\n  </button>\n  <button ng-click=\"ctrl.gridView()\" ng-class=\"{active: ctrl.mode === 'grid'}\">\n    <i class=\"fa fa-th\"></i>\n  </button>\n</div>\n";
var LayoutSelectorCtrl = /** @class */ (function () {
    /** @ngInject */
    function LayoutSelectorCtrl($rootScope) {
        this.$rootScope = $rootScope;
        this.mode = app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].get('grafana.list.layout.mode') || 'grid';
    }
    LayoutSelectorCtrl.prototype.listView = function () {
        this.mode = 'list';
        app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].set('grafana.list.layout.mode', 'list');
        this.$rootScope.appEvent('layout-mode-changed', 'list');
    };
    LayoutSelectorCtrl.prototype.gridView = function () {
        this.mode = 'grid';
        app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].set('grafana.list.layout.mode', 'grid');
        this.$rootScope.appEvent('layout-mode-changed', 'grid');
    };
    return LayoutSelectorCtrl;
}());

/** @ngInject */
function layoutSelector() {
    return {
        restrict: 'E',
        controller: LayoutSelectorCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {},
        template: template,
    };
}
/** @ngInject */
function layoutMode($rootScope) {
    return {
        restrict: 'A',
        scope: {},
        link: function (scope, elem) {
            var layout = app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].get('grafana.list.layout.mode') || 'grid';
            var className = 'card-list-layout-' + layout;
            elem.addClass(className);
            $rootScope.onAppEvent('layout-mode-changed', function (evt, newLayout) {
                elem.removeClass(className);
                className = 'card-list-layout-' + newLayout;
                elem.addClass(className);
            }, scope);
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('layoutSelector', layoutSelector);
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('layoutMode', layoutMode);


/***/ }),

/***/ "./public/app/core/components/manage_dashboards/manage_dashboards.ts":
/*!***************************************************************************!*\
  !*** ./public/app/core/components/manage_dashboards/manage_dashboards.ts ***!
  \***************************************************************************/
/*! exports provided: ManageDashboardsCtrl, manageDashboardsDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ManageDashboardsCtrl", function() { return ManageDashboardsCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "manageDashboardsDirective", function() { return manageDashboardsDirective; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");




var Query = /** @class */ (function () {
    function Query() {
    }
    return Query;
}());
var ManageDashboardsCtrl = /** @class */ (function () {
    /** @ngInject */
    function ManageDashboardsCtrl(backendSrv, navModelSrv, searchSrv, contextSrv) {
        var _this = this;
        this.backendSrv = backendSrv;
        this.searchSrv = searchSrv;
        this.contextSrv = contextSrv;
        this.selectAllChecked = false;
        // enable/disable actions depending on the folders or dashboards selected
        this.canDelete = false;
        this.canMove = false;
        // filter variables
        this.hasFilters = false;
        this.starredFilterOptions = [{ text: 'Filter by Starred', disabled: true }, { text: 'Yes' }, { text: 'No' }];
        // if user can add new folders and/or add new dashboards
        this.canSave = false;
        this.isEditor = this.contextSrv.isEditor;
        this.hasEditPermissionInFolders = this.contextSrv.hasEditPermissionInFolders;
        this.query = {
            query: '',
            mode: 'tree',
            tag: [],
            starred: false,
            skipRecent: true,
            skipStarred: true,
            folderIds: [],
        };
        if (this.folderId) {
            this.query.folderIds = [this.folderId];
        }
        this.selectedStarredFilter = this.starredFilterOptions[0];
        this.refreshList().then(function () {
            _this.initTagFilter();
        });
    }
    ManageDashboardsCtrl.prototype.refreshList = function () {
        var _this = this;
        return this.searchSrv
            .search(this.query)
            .then(function (result) {
            return _this.initDashboardList(result);
        })
            .then(function () {
            if (!_this.folderUid) {
                return;
            }
            return _this.backendSrv.getFolderByUid(_this.folderUid).then(function (folder) {
                _this.canSave = folder.canSave;
                if (!_this.canSave) {
                    _this.hasEditPermissionInFolders = false;
                }
            });
        });
    };
    ManageDashboardsCtrl.prototype.initDashboardList = function (result) {
        var e_1, _a, e_2, _b;
        this.canMove = false;
        this.canDelete = false;
        this.selectAllChecked = false;
        this.hasFilters = this.query.query.length > 0 || this.query.tag.length > 0 || this.query.starred;
        if (!result) {
            this.sections = [];
            return;
        }
        this.sections = result;
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.sections), _d = _c.next(); !_d.done; _d = _c.next()) {
                var section = _d.value;
                section.checked = false;
                try {
                    for (var _e = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](section.items)), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var dashboard = _f.value;
                        dashboard.checked = false;
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_1) throw e_1.error; }
        }
        if (this.folderId && this.sections.length > 0) {
            this.sections[0].hideHeader = true;
        }
    };
    ManageDashboardsCtrl.prototype.selectionChanged = function () {
        var e_3, _a;
        var selectedDashboards = 0;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
                var section = _c.value;
                selectedDashboards += lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(section.items, { checked: true }).length;
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
        var selectedFolders = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.sections, { checked: true }).length;
        this.canMove = selectedDashboards > 0;
        this.canDelete = selectedDashboards > 0 || selectedFolders > 0;
    };
    ManageDashboardsCtrl.prototype.getFoldersAndDashboardsToDelete = function () {
        var e_4, _a, _b;
        var selectedDashboards = {
            folderUids: [],
            dashboardUids: [],
        };
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.sections), _d = _c.next(); !_d.done; _d = _c.next()) {
                var section = _d.value;
                if (section.checked && section.id !== 0) {
                    selectedDashboards.folderUids.push(section.uid);
                }
                else {
                    var selected = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(section.items, { checked: true });
                    (_b = selectedDashboards.dashboardUids).push.apply(_b, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(selected, 'uid')));
                }
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_4) throw e_4.error; }
        }
        return selectedDashboards;
    };
    ManageDashboardsCtrl.prototype.getFolderIds = function (sections) {
        var e_5, _a;
        var ids = [];
        try {
            for (var sections_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](sections), sections_1_1 = sections_1.next(); !sections_1_1.done; sections_1_1 = sections_1.next()) {
                var s = sections_1_1.value;
                if (s.checked) {
                    ids.push(s.id);
                }
            }
        }
        catch (e_5_1) { e_5 = { error: e_5_1 }; }
        finally {
            try {
                if (sections_1_1 && !sections_1_1.done && (_a = sections_1.return)) _a.call(sections_1);
            }
            finally { if (e_5) throw e_5.error; }
        }
        return ids;
    };
    ManageDashboardsCtrl.prototype.delete = function () {
        var _this = this;
        var data = this.getFoldersAndDashboardsToDelete();
        var folderCount = data.folderUids.length;
        var dashCount = data.dashboardUids.length;
        var text = 'Do you want to delete the ';
        var text2;
        if (folderCount > 0 && dashCount > 0) {
            text += "selected folder" + (folderCount === 1 ? '' : 's') + " and dashboard" + (dashCount === 1 ? '' : 's') + "?";
            text2 = "All dashboards of the selected folder" + (folderCount === 1 ? '' : 's') + " will also be deleted";
        }
        else if (folderCount > 0) {
            text += "selected folder" + (folderCount === 1 ? '' : 's') + " and all its dashboards?";
        }
        else {
            text += "selected dashboard" + (dashCount === 1 ? '' : 's') + "?";
        }
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('confirm-modal', {
            title: 'Delete',
            text: text,
            text2: text2,
            icon: 'fa-trash',
            yesText: 'Delete',
            onConfirm: function () {
                _this.deleteFoldersAndDashboards(data.folderUids, data.dashboardUids);
            },
        });
    };
    ManageDashboardsCtrl.prototype.deleteFoldersAndDashboards = function (folderUids, dashboardUids) {
        var _this = this;
        this.backendSrv.deleteFoldersAndDashboards(folderUids, dashboardUids).then(function () {
            _this.refreshList();
        });
    };
    ManageDashboardsCtrl.prototype.getDashboardsToMove = function () {
        var e_6, _a;
        var selectedDashboards = [];
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
                var section = _c.value;
                var selected = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(section.items, { checked: true });
                selectedDashboards.push.apply(selectedDashboards, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(selected, 'uid')));
            }
        }
        catch (e_6_1) { e_6 = { error: e_6_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_6) throw e_6.error; }
        }
        return selectedDashboards;
    };
    ManageDashboardsCtrl.prototype.moveTo = function () {
        var selectedDashboards = this.getDashboardsToMove();
        var template = '<move-to-folder-modal dismiss="dismiss()" ' +
            'dashboards="model.dashboards" after-save="model.afterSave()">' +
            '</move-to-folder-modal>';
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('show-modal', {
            templateHtml: template,
            modalClass: 'modal--narrow',
            model: {
                dashboards: selectedDashboards,
                afterSave: this.refreshList.bind(this),
            },
        });
    };
    ManageDashboardsCtrl.prototype.initTagFilter = function () {
        var _this = this;
        return this.searchSrv.getDashboardTags().then(function (results) {
            _this.tagFilterOptions = [{ term: 'Filter By Tag', disabled: true }].concat(results);
            _this.selectedTagFilter = _this.tagFilterOptions[0];
        });
    };
    ManageDashboardsCtrl.prototype.filterByTag = function (tag) {
        if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.query.tag, tag) === -1) {
            this.query.tag.push(tag);
        }
        return this.refreshList();
    };
    ManageDashboardsCtrl.prototype.onQueryChange = function () {
        return this.refreshList();
    };
    ManageDashboardsCtrl.prototype.onTagFilterChange = function () {
        var res = this.filterByTag(this.selectedTagFilter.term);
        this.selectedTagFilter = this.tagFilterOptions[0];
        return res;
    };
    ManageDashboardsCtrl.prototype.removeTag = function (tag, evt) {
        this.query.tag = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.without(this.query.tag, tag);
        this.refreshList();
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };
    ManageDashboardsCtrl.prototype.removeStarred = function () {
        this.query.starred = false;
        return this.refreshList();
    };
    ManageDashboardsCtrl.prototype.onStarredFilterChange = function () {
        this.query.starred = this.selectedStarredFilter.text === 'Yes';
        this.selectedStarredFilter = this.starredFilterOptions[0];
        return this.refreshList();
    };
    ManageDashboardsCtrl.prototype.onSelectAllChanged = function () {
        var e_7, _a;
        var _this = this;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
                var section = _c.value;
                if (!section.hideHeader) {
                    section.checked = this.selectAllChecked;
                }
                section.items = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(section.items, function (item) {
                    item.checked = _this.selectAllChecked;
                    return item;
                });
            }
        }
        catch (e_7_1) { e_7 = { error: e_7_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_7) throw e_7.error; }
        }
        this.selectionChanged();
    };
    ManageDashboardsCtrl.prototype.clearFilters = function () {
        this.query.query = '';
        this.query.tag = [];
        this.query.starred = false;
        this.refreshList();
    };
    ManageDashboardsCtrl.prototype.createDashboardUrl = function () {
        var url = 'dashboard/new';
        if (this.folderId) {
            url += "?folderId=" + this.folderId;
        }
        return url;
    };
    ManageDashboardsCtrl.prototype.importDashboardUrl = function () {
        var url = 'dashboard/import';
        if (this.folderId) {
            url += "?folderId=" + this.folderId;
        }
        return url;
    };
    return ManageDashboardsCtrl;
}());

function manageDashboardsDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/core/components/manage_dashboards/manage_dashboards.html',
        controller: ManageDashboardsCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            folderId: '=',
            folderUid: '=',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('manageDashboards', manageDashboardsDirective);


/***/ }),

/***/ "./public/app/core/components/org_switcher.ts":
/*!****************************************************!*\
  !*** ./public/app/core/components/org_switcher.ts ***!
  \****************************************************/
/*! exports provided: OrgSwitchCtrl, orgSwitcher */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrgSwitchCtrl", function() { return OrgSwitchCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "orgSwitcher", function() { return orgSwitcher; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/services/context_srv */ "./public/app/core/services/context_srv.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



var template = "\n<div class=\"modal-body\">\n\t<div class=\"modal-header\">\n\t\t<h2 class=\"modal-header-title\">\n\t\t\t<i class=\"fa fa-random\"></i>\n\t\t\t<span class=\"p-l-1\">Switch Organization</span>\n\t\t</h2>\n\n\t\t<a class=\"modal-header-close\" ng-click=\"ctrl.dismiss();\">\n\t\t\t<i class=\"fa fa-remove\"></i>\n\t\t</a>\n\t</div>\n\n  <div class=\"modal-content modal-content--has-scroll\" grafana-scrollbar>\n    <table class=\"filter-table form-inline\">\n\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Name</th>\n\t\t\t\t\t<th>Role</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t</tr>\n\t\t\t</thead>\n\t\t\t<tbody>\n\t\t\t\t<tr ng-repeat=\"org in ctrl.orgs\">\n\t\t\t\t\t<td>{{org.name}}</td>\n\t\t\t\t\t<td>{{org.role}}</td>\n\t\t\t\t\t<td class=\"text-right\">\n\t\t\t\t\t\t<span class=\"btn btn-primary btn-small\" ng-show=\"org.orgId === ctrl.currentOrgId\">\n\t\t\t\t\t\t\tCurrent\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<a ng-click=\"ctrl.setUsingOrg(org)\" class=\"btn btn-inverse btn-small\" ng-show=\"org.orgId !== ctrl.currentOrgId\">\n\t\t\t\t\t\t\tSwitch to\n\t\t\t\t\t\t</a>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</tbody>\n\t\t</table>\n\t</div>\n</div>";
var OrgSwitchCtrl = /** @class */ (function () {
    /** @ngInject */
    function OrgSwitchCtrl(backendSrv) {
        this.backendSrv = backendSrv;
        this.currentOrgId = app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_1__["contextSrv"].user.orgId;
        this.getUserOrgs();
    }
    OrgSwitchCtrl.prototype.getUserOrgs = function () {
        var _this = this;
        this.backendSrv.get('/api/user/orgs').then(function (orgs) {
            _this.orgs = orgs;
        });
    };
    OrgSwitchCtrl.prototype.setUsingOrg = function (org) {
        var _this = this;
        return this.backendSrv.post('/api/user/using/' + org.orgId).then(function () {
            _this.setWindowLocation(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].appSubUrl + (app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].appSubUrl.endsWith('/') ? '' : '/') + '?orgId=' + org.orgId);
        });
    };
    OrgSwitchCtrl.prototype.setWindowLocation = function (href) {
        window.location.href = href;
    };
    return OrgSwitchCtrl;
}());

function orgSwitcher() {
    return {
        restrict: 'E',
        template: template,
        controller: OrgSwitchCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: { dismiss: '&' },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('orgSwitcher', orgSwitcher);


/***/ }),

/***/ "./public/app/core/components/query_part/query_part.ts":
/*!*************************************************************!*\
  !*** ./public/app/core/components/query_part/query_part.ts ***!
  \*************************************************************/
/*! exports provided: QueryPartDef, QueryPart, functionRenderer, suffixRenderer, identityRenderer, quotedIdentityRenderer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryPartDef", function() { return QueryPartDef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryPart", function() { return QueryPart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "functionRenderer", function() { return functionRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "suffixRenderer", function() { return suffixRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "identityRenderer", function() { return identityRenderer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "quotedIdentityRenderer", function() { return quotedIdentityRenderer; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

var QueryPartDef = /** @class */ (function () {
    function QueryPartDef(options) {
        this.type = options.type;
        this.params = options.params;
        this.defaultParams = options.defaultParams;
        this.renderer = options.renderer;
        this.category = options.category;
        this.addStrategy = options.addStrategy;
    }
    return QueryPartDef;
}());

var QueryPart = /** @class */ (function () {
    function QueryPart(part, def) {
        this.part = part;
        this.def = def;
        if (!this.def) {
            throw { message: 'Could not find query part ' + part.type };
        }
        part.params = part.params || lodash__WEBPACK_IMPORTED_MODULE_0___default.a.clone(this.def.defaultParams);
        this.params = part.params;
        this.updateText();
    }
    QueryPart.prototype.render = function (innerExpr) {
        return this.def.renderer(this, innerExpr);
    };
    QueryPart.prototype.hasMultipleParamsInString = function (strValue, index) {
        if (strValue.indexOf(',') === -1) {
            return false;
        }
        return this.def.params[index + 1] && this.def.params[index + 1].optional;
    };
    QueryPart.prototype.updateParam = function (strValue, index) {
        var _this = this;
        // handle optional parameters
        // if string contains ',' and next param is optional, split and update both
        if (this.hasMultipleParamsInString(strValue, index)) {
            lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(strValue.split(','), function (partVal, idx) {
                _this.updateParam(partVal.trim(), idx);
            });
            return;
        }
        if (strValue === '' && this.def.params[index].optional) {
            this.params.splice(index, 1);
        }
        else {
            this.params[index] = strValue;
        }
        this.part.params = this.params;
        this.updateText();
    };
    QueryPart.prototype.updateText = function () {
        if (this.params.length === 0) {
            this.text = this.def.type + '()';
            return;
        }
        var text = this.def.type + '(';
        text += this.params.join(', ');
        text += ')';
        this.text = text;
    };
    return QueryPart;
}());

function functionRenderer(part, innerExpr) {
    var str = part.def.type + '(';
    var parameters = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(part.params, function (value, index) {
        var paramType = part.def.params[index];
        if (paramType.type === 'time') {
            if (value === 'auto') {
                value = '$__interval';
            }
        }
        if (paramType.quote === 'single') {
            return "'" + value + "'";
        }
        else if (paramType.quote === 'double') {
            return '"' + value + '"';
        }
        return value;
    });
    if (innerExpr) {
        parameters.unshift(innerExpr);
    }
    return str + parameters.join(', ') + ')';
}
function suffixRenderer(part, innerExpr) {
    return innerExpr + ' ' + part.params[0];
}
function identityRenderer(part, innerExpr) {
    return part.params[0];
}
function quotedIdentityRenderer(part, innerExpr) {
    return '"' + part.params[0] + '"';
}


/***/ }),

/***/ "./public/app/core/components/query_part/query_part_editor.ts":
/*!********************************************************************!*\
  !*** ./public/app/core/components/query_part/query_part_editor.ts ***!
  \********************************************************************/
/*! exports provided: queryPartEditorDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryPartEditorDirective", function() { return queryPartEditorDirective; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");



var template = "\n<div class=\"dropdown cascade-open\">\n<a ng-click=\"showActionsMenu()\" class=\"query-part-name pointer dropdown-toggle\" data-toggle=\"dropdown\">{{part.def.type}}</a>\n<span>(</span><span class=\"query-part-parameters\"></span><span>)</span>\n<ul class=\"dropdown-menu\">\n  <li ng-repeat=\"action in partActions\">\n    <a ng-click=\"triggerPartAction(action)\">{{action.text}}</a>\n  </li>\n</ul>\n";
/** @ngInject */
function queryPartEditorDirective(templateSrv) {
    var paramTemplate = '<input type="text" class="hide input-mini tight-form-func-param"></input>';
    return {
        restrict: 'E',
        template: template,
        scope: {
            part: '=',
            handleEvent: '&',
            debounce: '@',
        },
        link: function postLink($scope, elem) {
            var part = $scope.part;
            var partDef = part.def;
            var $paramsContainer = elem.find('.query-part-parameters');
            var debounceLookup = $scope.debounce;
            $scope.partActions = [];
            function clickFuncParam(paramIndex) {
                /*jshint validthis:true */
                var $link = jquery__WEBPACK_IMPORTED_MODULE_1___default()(this);
                var $input = $link.next();
                $input.val(part.params[paramIndex]);
                $input.css('width', $link.width() + 16 + 'px');
                $link.hide();
                $input.show();
                $input.focus();
                $input.select();
                var typeahead = $input.data('typeahead');
                if (typeahead) {
                    $input.val('');
                    typeahead.lookup();
                }
            }
            function inputBlur(paramIndex) {
                /*jshint validthis:true */
                var $input = jquery__WEBPACK_IMPORTED_MODULE_1___default()(this);
                var $link = $input.prev();
                var newValue = $input.val();
                if (newValue !== '' || part.def.params[paramIndex].optional) {
                    $link.html(templateSrv.highlightVariablesAsHtml(newValue));
                    part.updateParam($input.val(), paramIndex);
                    $scope.$apply(function () {
                        $scope.handleEvent({ $event: { name: 'part-param-changed' } });
                    });
                }
                $input.hide();
                $link.show();
            }
            function inputKeyPress(paramIndex, e) {
                /*jshint validthis:true */
                if (e.which === 13) {
                    inputBlur.call(this, paramIndex);
                }
            }
            function inputKeyDown() {
                /*jshint validthis:true */
                this.style.width = (3 + this.value.length) * 8 + 'px';
            }
            function addTypeahead($input, param, paramIndex) {
                if (!param.options && !param.dynamicLookup) {
                    return;
                }
                var typeaheadSource = function (query, callback) {
                    if (param.options) {
                        var options = param.options;
                        if (param.type === 'int') {
                            options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(options, function (val) {
                                return val.toString();
                            });
                        }
                        return options;
                    }
                    $scope.$apply(function () {
                        $scope.handleEvent({ $event: { name: 'get-param-options' } }).then(function (result) {
                            var dynamicOptions = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(result, function (op) {
                                return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(op.value);
                            });
                            callback(dynamicOptions);
                        });
                    });
                };
                $input.attr('data-provide', 'typeahead');
                $input.typeahead({
                    source: typeaheadSource,
                    minLength: 0,
                    items: 1000,
                    updater: function (value) {
                        value = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.unescape(value);
                        setTimeout(function () {
                            inputBlur.call($input[0], paramIndex);
                        }, 0);
                        return value;
                    },
                });
                var typeahead = $input.data('typeahead');
                typeahead.lookup = function () {
                    this.query = this.$element.val() || '';
                    var items = this.source(this.query, jquery__WEBPACK_IMPORTED_MODULE_1___default.a.proxy(this.process, this));
                    return items ? this.process(items) : items;
                };
                if (debounceLookup) {
                    typeahead.lookup = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.debounce(typeahead.lookup, 500, { leading: true });
                }
            }
            $scope.showActionsMenu = function () {
                $scope.handleEvent({ $event: { name: 'get-part-actions' } }).then(function (res) {
                    $scope.partActions = res;
                });
            };
            $scope.triggerPartAction = function (action) {
                $scope.handleEvent({ $event: { name: 'action', action: action } });
            };
            function addElementsAndCompile() {
                lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(partDef.params, function (param, index) {
                    if (param.optional && part.params.length <= index) {
                        return;
                    }
                    if (index > 0) {
                        jquery__WEBPACK_IMPORTED_MODULE_1___default()('<span>, </span>').appendTo($paramsContainer);
                    }
                    var paramValue = templateSrv.highlightVariablesAsHtml(part.params[index]);
                    var $paramLink = jquery__WEBPACK_IMPORTED_MODULE_1___default()('<a class="graphite-func-param-link pointer">' + paramValue + '</a>');
                    var $input = jquery__WEBPACK_IMPORTED_MODULE_1___default()(paramTemplate);
                    $paramLink.appendTo($paramsContainer);
                    $input.appendTo($paramsContainer);
                    $input.blur(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partial(inputBlur, index));
                    $input.keyup(inputKeyDown);
                    $input.keypress(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partial(inputKeyPress, index));
                    $paramLink.click(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partial(clickFuncParam, index));
                    addTypeahead($input, param, index);
                });
            }
            function relink() {
                $paramsContainer.empty();
                addElementsAndCompile();
            }
            relink();
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('queryPartEditor', queryPartEditorDirective);


/***/ }),

/***/ "./public/app/core/components/scroll/scroll.ts":
/*!*****************************************************!*\
  !*** ./public/app/core/components/scroll/scroll.ts ***!
  \*****************************************************/
/*! exports provided: geminiScrollbar */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "geminiScrollbar", function() { return geminiScrollbar; });
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var baron__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! baron */ "./node_modules/baron/src/core.js");
/* harmony import */ var baron__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(baron__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

// @ts-ignore


var scrollBarHTML = "\n<div class=\"baron__track\">\n  <div class=\"baron__bar\"></div>\n</div>\n";
var scrollRootClass = 'baron baron__root';
var scrollerClass = 'baron__scroller';
function geminiScrollbar() {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            var scrollRoot = elem.parent();
            var scroller = elem;
            console.log('scroll');
            if (attrs.grafanaScrollbar && attrs.grafanaScrollbar === 'scrollonroot') {
                scrollRoot = scroller;
            }
            scrollRoot.addClass(scrollRootClass);
            jquery__WEBPACK_IMPORTED_MODULE_0___default()(scrollBarHTML).appendTo(scrollRoot);
            elem.addClass(scrollerClass);
            var scrollParams = {
                root: scrollRoot[0],
                scroller: scroller[0],
                bar: '.baron__bar',
                barOnCls: '_scrollbar',
                scrollingCls: '_scrolling',
                track: '.baron__track',
                direction: 'v',
            };
            var scrollbar = baron__WEBPACK_IMPORTED_MODULE_1___default()(scrollParams);
            scope.$on('$destroy', function () {
                scrollbar.dispose();
            });
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('grafanaScrollbar', geminiScrollbar);


/***/ }),

/***/ "./public/app/core/components/search/SearchField.tsx":
/*!***********************************************************!*\
  !*** ./public/app/core/components/search/SearchField.tsx ***!
  \***********************************************************/
/*! exports provided: SearchField */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SearchField", function() { return SearchField; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


// @ts-ignore



var getSearchFieldStyles = function (theme) { return ({
    wrapper: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    width: 100%;\n    height: 55px; /* this variable is not part of GrafanaTheme yet*/\n    display: flex;\n    background-color: ", ";\n    position: relative;\n  "], ["\n    width: 100%;\n    height: 55px; /* this variable is not part of GrafanaTheme yet*/\n    display: flex;\n    background-color: ",
        ";\n    position: relative;\n  "])), Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.white,
        dark: theme.colors.dark4,
    }, theme.type)),
    input: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    max-width: 653px;\n    padding: ", " ", " ", " ", ";\n    height: 51px;\n    box-sizing: border-box;\n    outline: none;\n    background: ", ";\n    background-color: ", ";\n    flex-grow: 10;\n  "], ["\n    max-width: 653px;\n    padding: ", " ", " ", " ", ";\n    height: 51px;\n    box-sizing: border-box;\n    outline: none;\n    background: ",
        ";\n    background-color: ",
        ";\n    flex-grow: 10;\n  "])), theme.spacing.md, theme.spacing.md, theme.spacing.sm, theme.spacing.md, Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: theme.colors.dark1,
        dark: theme.colors.black,
    }, theme.type), Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({
        light: tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(theme.colors.white)
            .lighten(4)
            .toString(),
        dark: theme.colors.dark4,
    }, theme.type)),
    spacer: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    flex-grow: 1;\n  "], ["\n    flex-grow: 1;\n  "]))),
    icon: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])(Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n      font-size: ", ";\n      padding: ", " ", " ", " ", ";\n    "], ["\n      font-size: ", ";\n      padding: ", " ", " ", " ", ";\n    "])), theme.typography.size.lg, theme.spacing.md, theme.spacing.md, theme.spacing.sm, theme.spacing.md), 'pointer'),
}); };
var SearchField = function (_a) {
    var query = _a.query, onChange = _a.onChange, inputProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["query", "onChange"]);
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var styles = getSearchFieldStyles(theme);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.wrapper + " search-field-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.icon },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-search" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ type: "text", placeholder: "Find dashboards by name", value: query.query, onChange: function (event) {
                    onChange(event.currentTarget.value);
                }, tabIndex: 1, spellCheck: false }, inputProps, { className: styles.input })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: styles.spacer }))));
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4;


/***/ }),

/***/ "./public/app/core/components/search/search.ts":
/*!*****************************************************!*\
  !*** ./public/app/core/components/search/search.ts ***!
  \*****************************************************/
/*! exports provided: SearchCtrl, searchDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SearchCtrl", function() { return SearchCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "searchDirective", function() { return searchDirective; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/services/context_srv */ "./public/app/core/services/context_srv.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var search_query_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! search-query-parser */ "./node_modules/search-query-parser/index.js");
/* harmony import */ var search_query_parser__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(search_query_parser__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/features/dashboard/services/DashboardSrv */ "./public/app/features/dashboard/services/DashboardSrv.ts");







var SearchQueryParser = /** @class */ (function () {
    function SearchQueryParser(config) {
        this.config = config;
    }
    SearchQueryParser.prototype.parse = function (query) {
        var parsedQuery = Object(search_query_parser__WEBPACK_IMPORTED_MODULE_5__["parse"])(query, this.config);
        if (typeof parsedQuery === 'string') {
            return {
                text: parsedQuery,
            };
        }
        return parsedQuery;
    };
    return SearchQueryParser;
}());
var SearchCtrl = /** @class */ (function () {
    /** @ngInject */
    function SearchCtrl($scope, $location, $timeout, searchSrv) {
        var _this = this;
        this.$location = $location;
        this.$timeout = $timeout;
        this.searchSrv = searchSrv;
        this.getTags = function () {
            return _this.searchSrv.getDashboardTags();
        };
        this.onTagFiltersChanged = function (tags) {
            _this.query.tags = tags;
            _this.search();
        };
        app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].on('show-dash-search', this.openSearch.bind(this), $scope);
        app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].on('hide-dash-search', this.closeSearch.bind(this), $scope);
        app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].on('search-query', Object(lodash__WEBPACK_IMPORTED_MODULE_1__["debounce"])(this.search.bind(this), 500), $scope);
        this.initialFolderFilterTitle = 'All';
        this.isEditor = app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].isEditor;
        this.hasEditPermissionInFolders = app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].hasEditPermissionInFolders;
        this.onQueryChange = this.onQueryChange.bind(this);
        this.onKeyDown = this.onKeyDown.bind(this);
        this.query = {
            query: '',
            parsedQuery: { text: '' },
            tags: [],
            starred: false,
        };
        this.queryParser = new SearchQueryParser({
            keywords: ['folder'],
        });
    }
    SearchCtrl.prototype.closeSearch = function () {
        this.isOpen = this.ignoreClose;
    };
    SearchCtrl.prototype.onQueryChange = function (query) {
        if (typeof query === 'string') {
            this.query = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.query, { parsedQuery: this.queryParser.parse(query), query: query });
        }
        else {
            this.query = query;
        }
        app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('search-query');
    };
    SearchCtrl.prototype.openSearch = function (payload) {
        var _this = this;
        if (payload === void 0) { payload = {}; }
        if (this.isOpen) {
            this.closeSearch();
            return;
        }
        this.isOpen = true;
        this.giveSearchFocus = true;
        this.selectedIndex = -1;
        this.results = [];
        this.query = {
            query: payload.query ? payload.query + " " : '',
            parsedQuery: this.queryParser.parse(payload.query),
            tags: [],
            starred: false,
        };
        this.currentSearchId = 0;
        this.ignoreClose = true;
        this.isLoading = true;
        this.$timeout(function () {
            _this.ignoreClose = false;
            _this.giveSearchFocus = true;
            _this.search();
        }, 100);
    };
    SearchCtrl.prototype.onKeyDown = function (evt) {
        if (evt.keyCode === 27) {
            this.closeSearch();
        }
        if (evt.keyCode === 40) {
            this.moveSelection(1);
        }
        if (evt.keyCode === 38) {
            this.moveSelection(-1);
        }
        if (evt.keyCode === 13) {
            var flattenedResult = this.getFlattenedResultForNavigation();
            var currentItem = flattenedResult[this.selectedIndex];
            if (currentItem) {
                if (currentItem.dashboardIndex !== undefined) {
                    var selectedDash = this.results[currentItem.folderIndex].items[currentItem.dashboardIndex];
                    if (selectedDash) {
                        this.$location.search({});
                        this.$location.path(selectedDash.url);
                        this.closeSearch();
                    }
                }
                else {
                    var selectedFolder = this.results[currentItem.folderIndex];
                    if (selectedFolder) {
                        selectedFolder.toggle(selectedFolder);
                    }
                }
            }
        }
    };
    SearchCtrl.prototype.onFilterboxClick = function () {
        this.giveSearchFocus = false;
        this.preventClose();
    };
    SearchCtrl.prototype.preventClose = function () {
        var _this = this;
        this.ignoreClose = true;
        this.$timeout(function () {
            _this.ignoreClose = false;
        }, 100);
    };
    SearchCtrl.prototype.moveSelection = function (direction) {
        if (this.results.length === 0) {
            return;
        }
        var flattenedResult = this.getFlattenedResultForNavigation();
        var currentItem = flattenedResult[this.selectedIndex];
        if (currentItem) {
            if (currentItem.dashboardIndex !== undefined) {
                this.results[currentItem.folderIndex].items[currentItem.dashboardIndex].selected = false;
            }
            else {
                this.results[currentItem.folderIndex].selected = false;
            }
        }
        if (direction === 0) {
            this.selectedIndex = -1;
            return;
        }
        var max = flattenedResult.length;
        var newIndex = (this.selectedIndex + direction) % max;
        this.selectedIndex = newIndex < 0 ? newIndex + max : newIndex;
        var selectedItem = flattenedResult[this.selectedIndex];
        if (selectedItem.dashboardIndex === undefined && this.results[selectedItem.folderIndex].id === 0) {
            this.moveSelection(direction);
            return;
        }
        if (selectedItem.dashboardIndex !== undefined) {
            if (!this.results[selectedItem.folderIndex].expanded) {
                this.moveSelection(direction);
                return;
            }
            this.results[selectedItem.folderIndex].items[selectedItem.dashboardIndex].selected = true;
            return;
        }
        if (this.results[selectedItem.folderIndex].hideHeader) {
            this.moveSelection(direction);
            return;
        }
        this.results[selectedItem.folderIndex].selected = true;
    };
    SearchCtrl.prototype.searchDashboards = function (folderContext) {
        var _this = this;
        this.currentSearchId = this.currentSearchId + 1;
        var localSearchId = this.currentSearchId;
        var folderIds = [];
        var parsedQuery = this.query.parsedQuery;
        if (folderContext === 'current') {
            folderIds.push(Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_6__["getDashboardSrv"])().getCurrent().meta.folderId);
        }
        var query = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.query, { query: parsedQuery.text, tag: this.query.tags, folderIds: folderIds });
        return this.searchSrv
            .search(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query))
            .then(function (results) {
            if (localSearchId < _this.currentSearchId) {
                return;
            }
            _this.results = results || [];
            _this.isLoading = false;
            _this.moveSelection(1);
        });
    };
    SearchCtrl.prototype.queryHasNoFilters = function () {
        var query = this.query;
        return query.query === '' && query.starred === false && query.tags.length === 0;
    };
    SearchCtrl.prototype.filterByTag = function (tag) {
        if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.query.tags, tag) === -1) {
            this.query.tags.push(tag);
            this.search();
        }
    };
    SearchCtrl.prototype.removeTag = function (tag, evt) {
        this.query.tags = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.without(this.query.tags, tag);
        this.search();
        this.giveSearchFocus = true;
        evt.stopPropagation();
        evt.preventDefault();
    };
    SearchCtrl.prototype.clearSearchFilter = function () {
        this.query.query = '';
        this.query.tags = [];
        this.search();
    };
    SearchCtrl.prototype.showStarred = function () {
        this.query.starred = !this.query.starred;
        this.giveSearchFocus = true;
        this.search();
    };
    SearchCtrl.prototype.search = function () {
        this.showImport = false;
        this.selectedIndex = -1;
        this.searchDashboards(this.query.parsedQuery['folder']);
    };
    SearchCtrl.prototype.folderExpanding = function () {
        this.moveSelection(0);
    };
    SearchCtrl.prototype.getFlattenedResultForNavigation = function () {
        var folderIndex = 0;
        return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.flatMap(this.results, function (s) {
            var result = [];
            result.push({
                folderIndex: folderIndex,
            });
            var dashboardIndex = 0;
            result = result.concat(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(s.items || [], function (i) {
                return {
                    folderIndex: folderIndex,
                    dashboardIndex: dashboardIndex++,
                };
            }));
            folderIndex++;
            return result;
        });
    };
    return SearchCtrl;
}());

function searchDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/core/components/search/search.html',
        controller: SearchCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {},
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('dashboardSearch', searchDirective);


/***/ }),

/***/ "./public/app/core/components/search/search_results.ts":
/*!*************************************************************!*\
  !*** ./public/app/core/components/search/search_results.ts ***!
  \*************************************************************/
/*! exports provided: SearchResultsCtrl, searchResultsDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SearchResultsCtrl", function() { return SearchResultsCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "searchResultsDirective", function() { return searchResultsDirective; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");



var SearchResultsCtrl = /** @class */ (function () {
    /** @ngInject */
    function SearchResultsCtrl($location) {
        this.$location = $location;
    }
    SearchResultsCtrl.prototype.toggleFolderExpand = function (section) {
        var _this = this;
        if (section.toggle) {
            if (!section.expanded && this.onFolderExpanding) {
                this.onFolderExpanding();
            }
            section.toggle(section).then(function (f) {
                if (_this.editable && f.expanded) {
                    if (f.items) {
                        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(f.items, function (i) {
                            i.checked = f.checked;
                        });
                        if (_this.onSelectionChanged) {
                            _this.onSelectionChanged();
                        }
                    }
                }
            });
        }
    };
    SearchResultsCtrl.prototype.navigateToFolder = function (section, evt) {
        this.$location.path(section.url);
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };
    SearchResultsCtrl.prototype.toggleSelection = function (item, evt) {
        item.checked = !item.checked;
        if (item.items) {
            lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(item.items, function (i) {
                i.checked = item.checked;
            });
        }
        if (this.onSelectionChanged) {
            this.onSelectionChanged();
        }
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };
    SearchResultsCtrl.prototype.onItemClick = function (item) {
        //Check if one string can be found in the other
        if (this.$location.path().indexOf(item.url) > -1 || item.url.indexOf(this.$location.path()) > -1) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('hide-dash-search');
        }
    };
    SearchResultsCtrl.prototype.selectTag = function (tag, evt) {
        if (this.onTagSelected) {
            this.onTagSelected({ $tag: tag });
        }
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };
    return SearchResultsCtrl;
}());

function searchResultsDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/core/components/search/search_results.html',
        controller: SearchResultsCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            editable: '@',
            results: '=',
            onSelectionChanged: '&',
            onTagSelected: '&',
            onFolderExpanding: '&',
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('dashboardSearchResults', searchResultsDirective);


/***/ }),

/***/ "./public/app/core/components/sidemenu/BottomNavLinks.tsx":
/*!****************************************************************!*\
  !*** ./public/app/core/components/sidemenu/BottomNavLinks.tsx ***!
  \****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../app_events */ "./public/app/core/app_events.ts");



var BottomNavLinks = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BottomNavLinks, _super);
    function BottomNavLinks() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.itemClicked = function (event, child) {
            if (child.url === '/shortcuts') {
                event.preventDefault();
                _app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('show-modal', {
                    templateHtml: '<help-modal></help-modal>',
                });
            }
        };
        _this.switchOrg = function () {
            _app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('show-modal', {
                templateHtml: '<org-switcher dismiss="dismiss()"></org-switcher>',
            });
        };
        return _this;
    }
    BottomNavLinks.prototype.render = function () {
        var _this = this;
        var _a = this.props, link = _a.link, user = _a.user;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "sidemenu-item dropdown dropup" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: link.url, className: "sidemenu-link", target: link.target },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "icon-circle sidemenu-icon" },
                    link.icon && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: link.icon }),
                    link.img && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { src: link.img }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", { className: "dropdown-menu dropdown-menu--sidemenu", role: "menu" },
                link.subTitle && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: "sidemenu-subtitle" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "sidemenu-item-text" }, link.subTitle))),
                link.showOrgSwitcher && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: "sidemenu-org-switcher" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { onClick: this.switchOrg },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "sidemenu-org-switcher__org-name" }, user.orgName),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "sidemenu-org-switcher__org-current" }, "Current Org:")),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "sidemenu-org-switcher__switch" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-random" }),
                            "Switch")))),
                link.children &&
                    link.children.map(function (child, index) {
                        if (!child.hideFromMenu) {
                            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { key: child.text + "-" + index },
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: child.url, target: child.target, onClick: function (event) { return _this.itemClicked(event, child); } },
                                    child.icon && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: child.icon }),
                                    child.text)));
                        }
                        return null;
                    }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: "side-menu-header" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "sidemenu-item-text" }, link.text)))));
    };
    return BottomNavLinks;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
/* harmony default export */ __webpack_exports__["default"] = (BottomNavLinks);


/***/ }),

/***/ "./public/app/core/components/sidemenu/BottomSection.tsx":
/*!***************************************************************!*\
  !*** ./public/app/core/components/sidemenu/BottomSection.tsx ***!
  \***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BottomSection; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _SignIn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SignIn */ "./public/app/core/components/sidemenu/SignIn.tsx");
/* harmony import */ var _BottomNavLinks__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./BottomNavLinks */ "./public/app/core/components/sidemenu/BottomNavLinks.tsx");
/* harmony import */ var app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/services/context_srv */ "./public/app/core/services/context_srv.ts");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../config */ "./public/app/core/config.ts");






function BottomSection() {
    var navTree = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(_config__WEBPACK_IMPORTED_MODULE_5__["default"].bootData.navTree);
    var bottomNav = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(navTree, function (item) { return item.hideFromMenu; });
    var isSignedIn = app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_4__["contextSrv"].isSignedIn;
    var user = app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_4__["contextSrv"].user;
    if (user && user.orgCount > 1) {
        var profileNode = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(bottomNav, { id: 'profile' });
        if (profileNode) {
            profileNode.showOrgSwitcher = true;
        }
    }
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "sidemenu__bottom" },
        !isSignedIn && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_SignIn__WEBPACK_IMPORTED_MODULE_2__["default"], null),
        bottomNav.map(function (link, index) {
            return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_BottomNavLinks__WEBPACK_IMPORTED_MODULE_3__["default"], { link: link, user: user, key: link.url + "-" + index });
        })));
}


/***/ }),

/***/ "./public/app/core/components/sidemenu/DropDownChild.tsx":
/*!***************************************************************!*\
  !*** ./public/app/core/components/sidemenu/DropDownChild.tsx ***!
  \***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var DropDownChild = function (props) {
    var child = props.child;
    var listItemClassName = child.divider ? 'divider' : '';
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", { className: listItemClassName },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: child.url },
            child.icon && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: child.icon }),
            child.text)));
};
/* harmony default export */ __webpack_exports__["default"] = (DropDownChild);


/***/ }),

/***/ "./public/app/core/components/sidemenu/SideMenu.tsx":
/*!**********************************************************!*\
  !*** ./public/app/core/components/sidemenu/SideMenu.tsx ***!
  \**********************************************************/
/*! exports provided: SideMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SideMenu", function() { return SideMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var _TopSection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./TopSection */ "./public/app/core/components/sidemenu/TopSection.tsx");
/* harmony import */ var _BottomSection__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./BottomSection */ "./public/app/core/components/sidemenu/BottomSection.tsx");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");






var homeUrl = app_core_config__WEBPACK_IMPORTED_MODULE_5__["default"].appSubUrl || '/';
var SideMenu = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SideMenu, _super);
    function SideMenu() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.toggleSideMenuSmallBreakpoint = function () {
            _app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('toggle-sidemenu-mobile');
        };
        return _this;
    }
    SideMenu.prototype.render = function () {
        return [
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: homeUrl, className: "sidemenu__logo", key: "logo" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { src: "public/img/grafana_icon.svg", alt: "Grafana" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "sidemenu__logo_small_breakpoint", onClick: this.toggleSideMenuSmallBreakpoint, key: "hamburger" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-bars" }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "sidemenu__close" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-times" }),
                    "\u00A0Close")),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TopSection__WEBPACK_IMPORTED_MODULE_3__["default"], { key: "topsection" }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_BottomSection__WEBPACK_IMPORTED_MODULE_4__["default"], { key: "bottomsection" }),
        ];
    };
    return SideMenu;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/core/components/sidemenu/SideMenuDropDown.tsx":
/*!******************************************************************!*\
  !*** ./public/app/core/components/sidemenu/SideMenuDropDown.tsx ***!
  \******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _DropDownChild__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DropDownChild */ "./public/app/core/components/sidemenu/DropDownChild.tsx");


var SideMenuDropDown = function (props) {
    var link = props.link;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", { className: "dropdown-menu dropdown-menu--sidemenu", role: "menu" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", { className: "side-menu-header" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { className: "side-menu-header-link", href: link.url },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "sidemenu-item-text" }, link.text))),
        link.children &&
            link.children.map(function (child, index) {
                return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_DropDownChild__WEBPACK_IMPORTED_MODULE_1__["default"], { child: child, key: child.url + "-" + index });
            })));
};
/* harmony default export */ __webpack_exports__["default"] = (SideMenuDropDown);


/***/ }),

/***/ "./public/app/core/components/sidemenu/SignIn.tsx":
/*!********************************************************!*\
  !*** ./public/app/core/components/sidemenu/SignIn.tsx ***!
  \********************************************************/
/*! exports provided: SignIn, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignIn", function() { return SignIn; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_connectWithReduxStore__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/connectWithReduxStore */ "./public/app/core/utils/connectWithReduxStore.tsx");


var SignIn = function (_a) {
    var url = _a.url;
    var loginUrl = "login?redirect=" + encodeURIComponent(url);
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "sidemenu-item" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: loginUrl, className: "sidemenu-link", target: "_self" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "icon-circle sidemenu-icon" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-fw fa-sign-in" }))),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { href: loginUrl, target: "_self" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", { className: "dropdown-menu dropdown-menu--sidemenu", role: "menu" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", { className: "side-menu-header" },
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "sidemenu-item-text" }, "Sign In"))))));
};
var mapStateToProps = function (state) { return ({
    url: state.location.url,
}); };
/* harmony default export */ __webpack_exports__["default"] = (Object(app_core_utils_connectWithReduxStore__WEBPACK_IMPORTED_MODULE_1__["connectWithStore"])(SignIn, mapStateToProps));


/***/ }),

/***/ "./public/app/core/components/sidemenu/TopSection.tsx":
/*!************************************************************!*\
  !*** ./public/app/core/components/sidemenu/TopSection.tsx ***!
  \************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _TopSectionItem__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TopSectionItem */ "./public/app/core/components/sidemenu/TopSectionItem.tsx");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../config */ "./public/app/core/config.ts");




var TopSection = function () {
    var navTree = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(_config__WEBPACK_IMPORTED_MODULE_3__["default"].bootData.navTree);
    var mainLinks = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(navTree, function (item) { return !item.hideFromMenu; });
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "sidemenu__top" }, mainLinks.map(function (link, index) {
        return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_TopSectionItem__WEBPACK_IMPORTED_MODULE_2__["default"], { link: link, key: link.id + "-" + index });
    })));
};
/* harmony default export */ __webpack_exports__["default"] = (TopSection);


/***/ }),

/***/ "./public/app/core/components/sidemenu/TopSectionItem.tsx":
/*!****************************************************************!*\
  !*** ./public/app/core/components/sidemenu/TopSectionItem.tsx ***!
  \****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _SideMenuDropDown__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SideMenuDropDown */ "./public/app/core/components/sidemenu/SideMenuDropDown.tsx");


var TopSectionItem = function (props) {
    var link = props.link;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "sidemenu-item dropdown" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { className: "sidemenu-link", href: link.url, target: link.target },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "icon-circle sidemenu-icon" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: link.icon }),
                link.img && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { src: link.img }))),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_SideMenuDropDown__WEBPACK_IMPORTED_MODULE_1__["default"], { link: link })));
};
/* harmony default export */ __webpack_exports__["default"] = (TopSectionItem);


/***/ }),

/***/ "./public/app/core/components/sql_part/sql_part_editor.ts":
/*!****************************************************************!*\
  !*** ./public/app/core/components/sql_part/sql_part_editor.ts ***!
  \****************************************************************/
/*! exports provided: sqlPartEditorDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sqlPartEditorDirective", function() { return sqlPartEditorDirective; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");



var template = "\n<div class=\"dropdown cascade-open\">\n<a ng-click=\"showActionsMenu()\" class=\"query-part-name pointer dropdown-toggle\" data-toggle=\"dropdown\">{{part.label}}</a>\n<span>{{part.def.wrapOpen}}</span><span class=\"query-part-parameters\"></span><span>{{part.def.wrapClose}}</span>\n<ul class=\"dropdown-menu\">\n  <li ng-repeat=\"action in partActions\">\n    <a ng-click=\"triggerPartAction(action)\">{{action.text}}</a>\n  </li>\n</ul>\n";
/** @ngInject */
function sqlPartEditorDirective(templateSrv) {
    var paramTemplate = '<input type="text" class="hide input-mini"></input>';
    return {
        restrict: 'E',
        template: template,
        scope: {
            part: '=',
            handleEvent: '&',
            debounce: '@',
        },
        link: function postLink($scope, elem) {
            var part = $scope.part;
            var partDef = part.def;
            var $paramsContainer = elem.find('.query-part-parameters');
            var debounceLookup = $scope.debounce;
            var cancelBlur = null;
            $scope.partActions = [];
            function clickFuncParam(paramIndex) {
                /*jshint validthis:true */
                var $link = jquery__WEBPACK_IMPORTED_MODULE_1___default()(this);
                var $input = $link.next();
                $input.val(part.params[paramIndex]);
                $input.css('width', $link.width() + 16 + 'px');
                $link.hide();
                $input.show();
                $input.focus();
                $input.select();
                var typeahead = $input.data('typeahead');
                if (typeahead) {
                    $input.val('');
                    typeahead.lookup();
                }
            }
            function inputBlur($input, paramIndex) {
                cancelBlur = setTimeout(function () {
                    switchToLink($input, paramIndex);
                }, 200);
            }
            function switchToLink($input, paramIndex) {
                /*jshint validthis:true */
                var $link = $input.prev();
                var newValue = $input.val();
                if (newValue !== '' || part.def.params[paramIndex].optional) {
                    $link.html(templateSrv.highlightVariablesAsHtml(newValue));
                    part.updateParam($input.val(), paramIndex);
                    $scope.$apply(function () {
                        $scope.handleEvent({ $event: { name: 'part-param-changed' } });
                    });
                }
                $input.hide();
                $link.show();
            }
            function inputKeyPress(paramIndex, e) {
                /*jshint validthis:true */
                if (e.which === 13) {
                    switchToLink(jquery__WEBPACK_IMPORTED_MODULE_1___default()(this), paramIndex);
                }
            }
            function inputKeyDown() {
                /*jshint validthis:true */
                this.style.width = (3 + this.value.length) * 8 + 'px';
            }
            function addTypeahead($input, param, paramIndex) {
                if (!param.options && !param.dynamicLookup) {
                    return;
                }
                var typeaheadSource = function (query, callback) {
                    if (param.options) {
                        var options = param.options;
                        if (param.type === 'int') {
                            options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(options, function (val) {
                                return val.toString();
                            });
                        }
                        return options;
                    }
                    $scope.$apply(function () {
                        $scope.handleEvent({ $event: { name: 'get-param-options', param: param } }).then(function (result) {
                            var dynamicOptions = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(result, function (op) {
                                return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(op.value);
                            });
                            // add current value to dropdown if it's not in dynamicOptions
                            if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.indexOf(dynamicOptions, part.params[paramIndex]) === -1) {
                                dynamicOptions.unshift(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(part.params[paramIndex]));
                            }
                            callback(dynamicOptions);
                        });
                    });
                };
                $input.attr('data-provide', 'typeahead');
                $input.typeahead({
                    source: typeaheadSource,
                    minLength: 0,
                    items: 1000,
                    updater: function (value) {
                        value = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.unescape(value);
                        if (value === part.params[paramIndex]) {
                            clearTimeout(cancelBlur);
                            $input.focus();
                            return value;
                        }
                        return value;
                    },
                });
                var typeahead = $input.data('typeahead');
                typeahead.lookup = function () {
                    this.query = this.$element.val() || '';
                    var items = this.source(this.query, jquery__WEBPACK_IMPORTED_MODULE_1___default.a.proxy(this.process, this));
                    return items ? this.process(items) : items;
                };
                if (debounceLookup) {
                    typeahead.lookup = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.debounce(typeahead.lookup, 500, { leading: true });
                }
            }
            $scope.showActionsMenu = function () {
                $scope.handleEvent({ $event: { name: 'get-part-actions' } }).then(function (res) {
                    $scope.partActions = res;
                });
            };
            $scope.triggerPartAction = function (action) {
                $scope.handleEvent({ $event: { name: 'action', action: action } });
            };
            function addElementsAndCompile() {
                lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(partDef.params, function (param, index) {
                    if (param.optional && part.params.length <= index) {
                        return;
                    }
                    if (index > 0) {
                        jquery__WEBPACK_IMPORTED_MODULE_1___default()('<span>' + partDef.separator + '</span>').appendTo($paramsContainer);
                    }
                    var paramValue = templateSrv.highlightVariablesAsHtml(part.params[index]);
                    var $paramLink = jquery__WEBPACK_IMPORTED_MODULE_1___default()('<a class="graphite-func-param-link pointer">' + paramValue + '</a>');
                    var $input = jquery__WEBPACK_IMPORTED_MODULE_1___default()(paramTemplate);
                    $paramLink.appendTo($paramsContainer);
                    $input.appendTo($paramsContainer);
                    $input.blur(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partial(inputBlur, $input, index));
                    $input.keyup(inputKeyDown);
                    $input.keypress(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partial(inputKeyPress, index));
                    $paramLink.click(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partial(clickFuncParam, index));
                    addTypeahead($input, param, index);
                });
            }
            function relink() {
                $paramsContainer.empty();
                addElementsAndCompile();
            }
            relink();
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('sqlPartEditor', sqlPartEditorDirective);


/***/ }),

/***/ "./public/app/core/components/switch.ts":
/*!**********************************************!*\
  !*** ./public/app/core/components/switch.ts ***!
  \**********************************************/
/*! exports provided: SwitchCtrl, switchDirective, checkboxDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SwitchCtrl", function() { return SwitchCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "switchDirective", function() { return switchDirective; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkboxDirective", function() { return checkboxDirective; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var template = "\n<label for=\"check-{{ctrl.id}}\" class=\"gf-form-switch-container\">\n  <div class=\"gf-form-label {{ctrl.labelClass}}\" ng-show=\"ctrl.label\">\n    {{ctrl.label}}\n    <info-popover mode=\"right-normal\" ng-if=\"ctrl.tooltip\" position=\"top center\">\n      {{ctrl.tooltip}}\n    </info-popover>\n  </div>\n  <div class=\"gf-form-switch {{ctrl.switchClass}}\" ng-if=\"ctrl.show\">\n    <input id=\"check-{{ctrl.id}}\" type=\"checkbox\" ng-model=\"ctrl.checked\" ng-change=\"ctrl.internalOnChange()\">\n    <span class=\"gf-form-switch__slider\"></span>\n  </div>\n</label>\n";
var checkboxTemplate = "\n<label for=\"check-{{ctrl.id}}\" class=\"gf-form-switch-container\">\n   <div class=\"gf-form-label {{ctrl.labelClass}}\" ng-show=\"ctrl.label\">\n    {{ctrl.label}}\n    <info-popover mode=\"right-normal\" ng-if=\"ctrl.tooltip\" position=\"top center\">\n      {{ctrl.tooltip}}\n    </info-popover>\n  </div>\n  <div class=\"gf-form-checkbox {{ctrl.switchClass}}\" ng-if=\"ctrl.show\">\n    <input id=\"check-{{ctrl.id}}\" type=\"checkbox\" ng-model=\"ctrl.checked\" ng-change=\"ctrl.internalOnChange()\">\n    <span class=\"gf-form-switch__checkbox\"></span>\n  </div>\n</label>\n";
var SwitchCtrl = /** @class */ (function () {
    /** @ngInject */
    function SwitchCtrl($scope, $timeout) {
        this.$timeout = $timeout;
        this.show = true;
        this.id = $scope.$id;
    }
    SwitchCtrl.prototype.internalOnChange = function () {
        var _this = this;
        return this.$timeout(function () {
            return _this.onChange();
        });
    };
    return SwitchCtrl;
}());

function switchDirective() {
    return {
        restrict: 'E',
        controller: SwitchCtrl,
        controllerAs: 'ctrl',
        bindToController: true,
        scope: {
            checked: '=',
            label: '@',
            labelClass: '@',
            tooltip: '@',
            switchClass: '@',
            onChange: '&',
        },
        template: template,
    };
}
function checkboxDirective() {
    return {
        restrict: 'E',
        controller: SwitchCtrl,
        controllerAs: 'ctrl',
        bindToController: true,
        scope: {
            checked: '=',
            label: '@',
            labelClass: '@',
            tooltip: '@',
            switchClass: '@',
            onChange: '&',
        },
        template: checkboxTemplate,
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('gfFormSwitch', switchDirective);
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('gfFormCheckbox', checkboxDirective);


/***/ }),

/***/ "./public/app/core/config.ts":
/*!***********************************!*\
  !*** ./public/app/core/config.ts ***!
  \***********************************/
/*! exports provided: config, Settings, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "config", function() { return _grafana_runtime__WEBPACK_IMPORTED_MODULE_0__["config"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return _grafana_runtime__WEBPACK_IMPORTED_MODULE_0__["GrafanaBootConfig"]; });


// Legacy binding paths

/* harmony default export */ __webpack_exports__["default"] = (_grafana_runtime__WEBPACK_IMPORTED_MODULE_0__["config"]);


/***/ }),

/***/ "./public/app/core/constants.ts":
/*!**************************************!*\
  !*** ./public/app/core/constants.ts ***!
  \**************************************/
/*! exports provided: GRID_CELL_HEIGHT, GRID_CELL_VMARGIN, GRID_COLUMN_COUNT, REPEAT_DIR_VERTICAL, DEFAULT_PANEL_SPAN, DEFAULT_ROW_HEIGHT, MIN_PANEL_HEIGHT, LS_PANEL_COPY_KEY, PANEL_BORDER */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GRID_CELL_HEIGHT", function() { return GRID_CELL_HEIGHT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GRID_CELL_VMARGIN", function() { return GRID_CELL_VMARGIN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GRID_COLUMN_COUNT", function() { return GRID_COLUMN_COUNT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "REPEAT_DIR_VERTICAL", function() { return REPEAT_DIR_VERTICAL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_PANEL_SPAN", function() { return DEFAULT_PANEL_SPAN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_ROW_HEIGHT", function() { return DEFAULT_ROW_HEIGHT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MIN_PANEL_HEIGHT", function() { return MIN_PANEL_HEIGHT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LS_PANEL_COPY_KEY", function() { return LS_PANEL_COPY_KEY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PANEL_BORDER", function() { return PANEL_BORDER; });
var GRID_CELL_HEIGHT = 30;
var GRID_CELL_VMARGIN = 10;
var GRID_COLUMN_COUNT = 24;
var REPEAT_DIR_VERTICAL = 'v';
var DEFAULT_PANEL_SPAN = 4;
var DEFAULT_ROW_HEIGHT = 250;
var MIN_PANEL_HEIGHT = GRID_CELL_HEIGHT * 3;
var LS_PANEL_COPY_KEY = 'panel-copy';
var PANEL_BORDER = 2;


/***/ }),

/***/ "./public/app/core/controllers/all.ts":
/*!********************************************!*\
  !*** ./public/app/core/controllers/all.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _json_editor_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./json_editor_ctrl */ "./public/app/core/controllers/json_editor_ctrl.ts");
/* harmony import */ var _invited_ctrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./invited_ctrl */ "./public/app/core/controllers/invited_ctrl.ts");
/* harmony import */ var _signup_ctrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./signup_ctrl */ "./public/app/core/controllers/signup_ctrl.ts");
/* harmony import */ var _reset_password_ctrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./reset_password_ctrl */ "./public/app/core/controllers/reset_password_ctrl.ts");
/* harmony import */ var _error_ctrl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./error_ctrl */ "./public/app/core/controllers/error_ctrl.ts");







/***/ }),

/***/ "./public/app/core/controllers/error_ctrl.ts":
/*!***************************************************!*\
  !*** ./public/app/core/controllers/error_ctrl.ts ***!
  \***************************************************/
/*! exports provided: ErrorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorCtrl", function() { return ErrorCtrl; });
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");



var ErrorCtrl = /** @class */ (function () {
    /** @ngInject */
    function ErrorCtrl($scope, contextSrv, navModelSrv) {
        $scope.navModel = navModelSrv.getNotFoundNav();
        $scope.appSubUrl = app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].appSubUrl;
        if (!contextSrv.isSignedIn) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('toggle-sidemenu-hidden');
        }
        $scope.$on('destroy', function () {
            if (!contextSrv.isSignedIn) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('toggle-sidemenu-hidden');
            }
        });
    }
    return ErrorCtrl;
}());

_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].controller('ErrorCtrl', ErrorCtrl);


/***/ }),

/***/ "./public/app/core/controllers/invited_ctrl.ts":
/*!*****************************************************!*\
  !*** ./public/app/core/controllers/invited_ctrl.ts ***!
  \*****************************************************/
/*! exports provided: InvitedCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InvitedCtrl", function() { return InvitedCtrl; });
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");


var InvitedCtrl = /** @class */ (function () {
    /** @ngInject */
    function InvitedCtrl($scope, $routeParams, contextSrv, backendSrv) {
        contextSrv.sidemenu = false;
        $scope.formModel = {};
        $scope.navModel = {
            main: {
                icon: 'gicon gicon-branding',
                text: 'Invite',
                subTitle: 'Register your Grafana account',
                breadcrumbs: [{ title: 'Login', url: 'login' }],
            },
        };
        $scope.init = function () {
            backendSrv.get('/api/user/invite/' + $routeParams.code).then(function (invite) {
                $scope.formModel.name = invite.name;
                $scope.formModel.email = invite.email;
                $scope.formModel.username = invite.email;
                $scope.formModel.inviteCode = $routeParams.code;
                $scope.greeting = invite.name || invite.email || invite.username;
                $scope.invitedBy = invite.invitedBy;
            });
        };
        $scope.submit = function () {
            if (!$scope.inviteForm.$valid) {
                return;
            }
            backendSrv.post('/api/user/invite/complete', $scope.formModel).then(function () {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/';
            });
        };
        $scope.init();
    }
    return InvitedCtrl;
}());

_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].controller('InvitedCtrl', InvitedCtrl);


/***/ }),

/***/ "./public/app/core/controllers/json_editor_ctrl.ts":
/*!*********************************************************!*\
  !*** ./public/app/core/controllers/json_editor_ctrl.ts ***!
  \*********************************************************/
/*! exports provided: JsonEditorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JsonEditorCtrl", function() { return JsonEditorCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


var JsonEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function JsonEditorCtrl($scope) {
        $scope.json = angular__WEBPACK_IMPORTED_MODULE_0___default.a.toJson($scope.model.object, true);
        $scope.canUpdate = $scope.model.updateHandler !== void 0 && $scope.model.canUpdate;
        $scope.canCopy = $scope.model.enableCopy;
        $scope.update = function () {
            var newObject = angular__WEBPACK_IMPORTED_MODULE_0___default.a.fromJson($scope.json);
            $scope.model.updateHandler(newObject, $scope.model.object);
        };
        $scope.getContentForClipboard = function () { return $scope.json; };
    }
    return JsonEditorCtrl;
}());

_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].controller('JsonEditorCtrl', JsonEditorCtrl);


/***/ }),

/***/ "./public/app/core/controllers/reset_password_ctrl.ts":
/*!************************************************************!*\
  !*** ./public/app/core/controllers/reset_password_ctrl.ts ***!
  \************************************************************/
/*! exports provided: ResetPasswordCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResetPasswordCtrl", function() { return ResetPasswordCtrl; });
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");


var ResetPasswordCtrl = /** @class */ (function () {
    /** @ngInject */
    function ResetPasswordCtrl($scope, backendSrv, $location) {
        $scope.formModel = {};
        $scope.mode = 'send';
        $scope.ldapEnabled = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].ldapEnabled;
        $scope.authProxyEnabled = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].authProxyEnabled;
        $scope.disableLoginForm = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].disableLoginForm;
        var params = $location.search();
        if (params.code) {
            $scope.mode = 'reset';
            $scope.formModel.code = params.code;
        }
        $scope.navModel = {
            main: {
                icon: 'gicon gicon-branding',
                text: 'Reset Password',
                subTitle: 'Reset your Grafana password',
                breadcrumbs: [{ title: 'Login', url: 'login' }],
            },
        };
        $scope.sendResetEmail = function () {
            if (!$scope.sendResetForm.$valid) {
                return;
            }
            backendSrv.post('/api/user/password/send-reset-email', $scope.formModel).then(function () {
                $scope.mode = 'email-sent';
            });
        };
        $scope.submitReset = function () {
            if (!$scope.resetForm.$valid) {
                return;
            }
            if ($scope.formModel.newPassword !== $scope.formModel.confirmPassword) {
                $scope.appEvent('alert-warning', ['New passwords do not match', '']);
                return;
            }
            backendSrv.post('/api/user/password/reset', $scope.formModel).then(function () {
                $location.path('login');
            });
        };
    }
    return ResetPasswordCtrl;
}());

_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].controller('ResetPasswordCtrl', ResetPasswordCtrl);


/***/ }),

/***/ "./public/app/core/controllers/signup_ctrl.ts":
/*!****************************************************!*\
  !*** ./public/app/core/controllers/signup_ctrl.ts ***!
  \****************************************************/
/*! exports provided: SignUpCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignUpCtrl", function() { return SignUpCtrl; });
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


var SignUpCtrl = /** @class */ (function () {
    /** @ngInject */
    function SignUpCtrl($scope, backendSrv, $location, contextSrv) {
        this.$scope = $scope;
        this.backendSrv = backendSrv;
        contextSrv.sidemenu = false;
        $scope.ctrl = this;
        $scope.formModel = {};
        var params = $location.search();
        // validate email is semi ok
        if (params.email && !params.email.match(/^\S+@\S+$/)) {
            console.log('invalid email');
            return;
        }
        $scope.formModel.orgName = params.email;
        $scope.formModel.email = params.email;
        $scope.formModel.username = params.email;
        $scope.formModel.code = params.code;
        $scope.verifyEmailEnabled = false;
        $scope.autoAssignOrg = false;
        $scope.navModel = {
            main: {
                icon: 'gicon gicon-branding',
                text: 'Sign Up',
                subTitle: 'Register your Grafana account',
                breadcrumbs: [{ title: 'Login', url: 'login' }],
            },
        };
        backendSrv.get('/api/user/signup/options').then(function (options) {
            $scope.verifyEmailEnabled = options.verifyEmailEnabled;
            $scope.autoAssignOrg = options.autoAssignOrg;
        });
    }
    SignUpCtrl.prototype.submit = function () {
        if (!this.$scope.signUpForm.$valid) {
            return;
        }
        this.backendSrv.post('/api/user/signup/step2', this.$scope.formModel).then(function (rsp) {
            if (rsp.code === 'redirect-to-select-org') {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].appSubUrl + '/profile/select-org?signup=1';
            }
            else {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].appSubUrl + '/';
            }
        });
    };
    return SignUpCtrl;
}());

_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].controller('SignUpCtrl', SignUpCtrl);


/***/ }),

/***/ "./public/app/core/copy/appNotification.ts":
/*!*************************************************!*\
  !*** ./public/app/core/copy/appNotification.ts ***!
  \*************************************************/
/*! exports provided: createSuccessNotification, createErrorNotification, createWarningNotification */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createSuccessNotification", function() { return createSuccessNotification; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createErrorNotification", function() { return createErrorNotification; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createWarningNotification", function() { return createWarningNotification; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var app_core_utils_errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/errors */ "./public/app/core/utils/errors.ts");



var defaultSuccessNotification = {
    title: '',
    text: '',
    severity: app_types__WEBPACK_IMPORTED_MODULE_1__["AppNotificationSeverity"].Success,
    icon: 'fa fa-check',
    timeout: app_types__WEBPACK_IMPORTED_MODULE_1__["AppNotificationTimeout"].Success,
};
var defaultWarningNotification = {
    title: '',
    text: '',
    severity: app_types__WEBPACK_IMPORTED_MODULE_1__["AppNotificationSeverity"].Warning,
    icon: 'fa fa-exclamation',
    timeout: app_types__WEBPACK_IMPORTED_MODULE_1__["AppNotificationTimeout"].Warning,
};
var defaultErrorNotification = {
    title: '',
    text: '',
    severity: app_types__WEBPACK_IMPORTED_MODULE_1__["AppNotificationSeverity"].Error,
    icon: 'fa fa-exclamation-triangle',
    timeout: app_types__WEBPACK_IMPORTED_MODULE_1__["AppNotificationTimeout"].Error,
};
var createSuccessNotification = function (title, text) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaultSuccessNotification, { title: title, text: text, id: Date.now() })); };
var createErrorNotification = function (title, text) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaultErrorNotification, { title: title, text: Object(app_core_utils_errors__WEBPACK_IMPORTED_MODULE_2__["getMessageFromError"])(text), id: Date.now() });
};
var createWarningNotification = function (title, text) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaultWarningNotification, { title: title, text: text, id: Date.now() })); };


/***/ }),

/***/ "./public/app/core/core.ts":
/*!*********************************!*\
  !*** ./public/app/core/core.ts ***!
  \*********************************/
/*! exports provided: profiler, registerAngularDirectives, arrayJoin, coreModule, searchDirective, liveSrv, layoutSelector, switchDirective, infoPopover, Emitter, appEvents, dashboardSelector, queryPartEditorDirective, sqlPartEditorDirective, colors, formDropdownDirective, assignModelProperties, contextSrv, KeybindingSrv, helpModal, JsonExplorer, NavModelSrv, NavModel, geminiScrollbar, orgSwitcher, manageDashboardsDirective, TimeSeries, updateLegendValues, searchResultsDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _directives_dropdown_typeahead__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./directives/dropdown_typeahead */ "./public/app/core/directives/dropdown_typeahead.ts");
/* harmony import */ var _directives_autofill_event_fix__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./directives/autofill_event_fix */ "./public/app/core/directives/autofill_event_fix.ts");
/* harmony import */ var _directives_metric_segment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./directives/metric_segment */ "./public/app/core/directives/metric_segment.ts");
/* harmony import */ var _directives_misc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./directives/misc */ "./public/app/core/directives/misc.ts");
/* harmony import */ var _directives_ng_model_on_blur__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./directives/ng_model_on_blur */ "./public/app/core/directives/ng_model_on_blur.ts");
/* harmony import */ var _directives_tags__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directives/tags */ "./public/app/core/directives/tags.ts");
/* harmony import */ var _directives_value_select_dropdown__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./directives/value_select_dropdown */ "./public/app/core/directives/value_select_dropdown.ts");
/* harmony import */ var _directives_rebuild_on_change__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./directives/rebuild_on_change */ "./public/app/core/directives/rebuild_on_change.ts");
/* harmony import */ var _directives_give_focus__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./directives/give_focus */ "./public/app/core/directives/give_focus.ts");
/* harmony import */ var _directives_diff_view__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./directives/diff-view */ "./public/app/core/directives/diff-view.ts");
/* harmony import */ var _jquery_extended__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./jquery_extended */ "./public/app/core/jquery_extended.ts");
/* harmony import */ var _partials__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./partials */ "./public/app/core/partials.ts");
/* harmony import */ var _partials__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_partials__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _components_jsontree_jsontree__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./components/jsontree/jsontree */ "./public/app/core/components/jsontree/jsontree.ts");
/* harmony import */ var _components_code_editor_code_editor__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./components/code_editor/code_editor */ "./public/app/core/components/code_editor/code_editor.ts");
/* harmony import */ var _utils_outline__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/outline */ "./public/app/core/utils/outline.ts");
/* harmony import */ var _utils_outline__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_utils_outline__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _components_colorpicker_spectrum_picker__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./components/colorpicker/spectrum_picker */ "./public/app/core/components/colorpicker/spectrum_picker.ts");
/* harmony import */ var _services_search_srv__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./services/search_srv */ "./public/app/core/services/search_srv.ts");
/* harmony import */ var _services_ng_react__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./services/ng_react */ "./public/app/core/services/ng_react.ts");
/* harmony import */ var _grafana_ui___WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @grafana/ui/ */ "./packages/grafana-ui/src/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "colors", function() { return _grafana_ui___WEBPACK_IMPORTED_MODULE_18__["colors"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JsonExplorer", function() { return _grafana_ui___WEBPACK_IMPORTED_MODULE_18__["JsonExplorer"]; });

/* harmony import */ var _components_search_search__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./components/search/search */ "./public/app/core/components/search/search.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "searchDirective", function() { return _components_search_search__WEBPACK_IMPORTED_MODULE_19__["searchDirective"]; });

/* harmony import */ var _components_info_popover__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./components/info_popover */ "./public/app/core/components/info_popover.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "infoPopover", function() { return _components_info_popover__WEBPACK_IMPORTED_MODULE_20__["infoPopover"]; });

/* harmony import */ var _directives_array_join__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./directives/array_join */ "./public/app/core/directives/array_join.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "arrayJoin", function() { return _directives_array_join__WEBPACK_IMPORTED_MODULE_21__["arrayJoin"]; });

/* harmony import */ var _live_live_srv__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./live/live_srv */ "./public/app/core/live/live_srv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "liveSrv", function() { return _live_live_srv__WEBPACK_IMPORTED_MODULE_22__["liveSrv"]; });

/* harmony import */ var _utils_emitter__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./utils/emitter */ "./public/app/core/utils/emitter.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Emitter", function() { return _utils_emitter__WEBPACK_IMPORTED_MODULE_23__["Emitter"]; });

/* harmony import */ var _components_layout_selector_layout_selector__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./components/layout_selector/layout_selector */ "./public/app/core/components/layout_selector/layout_selector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "layoutSelector", function() { return _components_layout_selector_layout_selector__WEBPACK_IMPORTED_MODULE_24__["layoutSelector"]; });

/* harmony import */ var _components_switch__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./components/switch */ "./public/app/core/components/switch.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "switchDirective", function() { return _components_switch__WEBPACK_IMPORTED_MODULE_25__["switchDirective"]; });

/* harmony import */ var _components_dashboard_selector__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./components/dashboard_selector */ "./public/app/core/components/dashboard_selector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dashboardSelector", function() { return _components_dashboard_selector__WEBPACK_IMPORTED_MODULE_26__["dashboardSelector"]; });

/* harmony import */ var _components_query_part_query_part_editor__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./components/query_part/query_part_editor */ "./public/app/core/components/query_part/query_part_editor.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "queryPartEditorDirective", function() { return _components_query_part_query_part_editor__WEBPACK_IMPORTED_MODULE_27__["queryPartEditorDirective"]; });

/* harmony import */ var _components_sql_part_sql_part_editor__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./components/sql_part/sql_part_editor */ "./public/app/core/components/sql_part/sql_part_editor.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "sqlPartEditorDirective", function() { return _components_sql_part_sql_part_editor__WEBPACK_IMPORTED_MODULE_28__["sqlPartEditorDirective"]; });

/* harmony import */ var _components_form_dropdown_form_dropdown__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./components/form_dropdown/form_dropdown */ "./public/app/core/components/form_dropdown/form_dropdown.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "formDropdownDirective", function() { return _components_form_dropdown_form_dropdown__WEBPACK_IMPORTED_MODULE_29__["formDropdownDirective"]; });

/* harmony import */ var app_core_controllers_all__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! app/core/controllers/all */ "./public/app/core/controllers/all.ts");
/* harmony import */ var app_core_services_all__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! app/core/services/all */ "./public/app/core/services/all.ts");
/* harmony import */ var _filters_filters__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./filters/filters */ "./public/app/core/filters/filters.ts");
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./core_module */ "./public/app/core/core_module.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "coreModule", function() { return _core_module__WEBPACK_IMPORTED_MODULE_33__["default"]; });

/* harmony import */ var _app_events__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./app_events */ "./public/app/core/app_events.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "appEvents", function() { return _app_events__WEBPACK_IMPORTED_MODULE_34__["default"]; });

/* harmony import */ var _utils_model_utils__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./utils/model_utils */ "./public/app/core/utils/model_utils.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "assignModelProperties", function() { return _utils_model_utils__WEBPACK_IMPORTED_MODULE_35__["assignModelProperties"]; });

/* harmony import */ var _services_context_srv__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./services/context_srv */ "./public/app/core/services/context_srv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "contextSrv", function() { return _services_context_srv__WEBPACK_IMPORTED_MODULE_36__["contextSrv"]; });

/* harmony import */ var _services_keybindingSrv__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./services/keybindingSrv */ "./public/app/core/services/keybindingSrv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeybindingSrv", function() { return _services_keybindingSrv__WEBPACK_IMPORTED_MODULE_37__["KeybindingSrv"]; });

/* harmony import */ var _components_help_help__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./components/help/help */ "./public/app/core/components/help/help.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "helpModal", function() { return _components_help_help__WEBPACK_IMPORTED_MODULE_38__["helpModal"]; });

/* harmony import */ var _nav_model_srv__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./nav_model_srv */ "./public/app/core/nav_model_srv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NavModelSrv", function() { return _nav_model_srv__WEBPACK_IMPORTED_MODULE_39__["NavModelSrv"]; });

/* harmony import */ var _components_scroll_scroll__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./components/scroll/scroll */ "./public/app/core/components/scroll/scroll.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "geminiScrollbar", function() { return _components_scroll_scroll__WEBPACK_IMPORTED_MODULE_40__["geminiScrollbar"]; });

/* harmony import */ var _components_org_switcher__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./components/org_switcher */ "./public/app/core/components/org_switcher.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "orgSwitcher", function() { return _components_org_switcher__WEBPACK_IMPORTED_MODULE_41__["orgSwitcher"]; });

/* harmony import */ var _profiler__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./profiler */ "./public/app/core/profiler.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "profiler", function() { return _profiler__WEBPACK_IMPORTED_MODULE_42__["profiler"]; });

/* harmony import */ var _angular_wrappers__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./angular_wrappers */ "./public/app/core/angular_wrappers.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "registerAngularDirectives", function() { return _angular_wrappers__WEBPACK_IMPORTED_MODULE_43__["registerAngularDirectives"]; });

/* harmony import */ var _time_series2__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./time_series2 */ "./public/app/core/time_series2.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "updateLegendValues", function() { return _time_series2__WEBPACK_IMPORTED_MODULE_44__["updateLegendValues"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimeSeries", function() { return _time_series2__WEBPACK_IMPORTED_MODULE_44__["default"]; });

/* harmony import */ var _components_search_search_results__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./components/search/search_results */ "./public/app/core/components/search/search_results.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "searchResultsDirective", function() { return _components_search_search_results__WEBPACK_IMPORTED_MODULE_45__["searchResultsDirective"]; });

/* harmony import */ var _components_manage_dashboards_manage_dashboards__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./components/manage_dashboards/manage_dashboards */ "./public/app/core/components/manage_dashboards/manage_dashboards.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "manageDashboardsDirective", function() { return _components_manage_dashboards_manage_dashboards__WEBPACK_IMPORTED_MODULE_46__["manageDashboardsDirective"]; });

/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NavModel", function() { return _grafana_data__WEBPACK_IMPORTED_MODULE_47__["NavModel"]; });





















































/***/ }),

/***/ "./public/app/core/core_module.ts":
/*!****************************************!*\
  !*** ./public/app/core/core_module.ts ***!
  \****************************************/
/*! exports provided: angularModules, coreModule, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "angularModules", function() { return angularModules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "coreModule", function() { return coreModule; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);

var coreModule = angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.core', ['ngRoute']);
// legacy modules
var angularModules = [
    coreModule,
    angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.controllers', []),
    angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives', []),
    angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.factories', []),
    angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.services', []),
    angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.filters', []),
    angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.routes', []),
];

/* harmony default export */ __webpack_exports__["default"] = (coreModule);


/***/ }),

/***/ "./public/app/core/directives/array_join.ts":
/*!**************************************************!*\
  !*** ./public/app/core/directives/array_join.ts ***!
  \**************************************************/
/*! exports provided: arrayJoin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayJoin", function() { return arrayJoin; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


function arrayJoin() {
    'use strict';
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
            function split_array(text) {
                return (text || '').split(',');
            }
            function join_array(text) {
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(text)) {
                    return (text || '').join(',');
                }
                else {
                    return text;
                }
            }
            ngModel.$parsers.push(split_array);
            ngModel.$formatters.push(join_array);
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('arrayJoin', arrayJoin);


/***/ }),

/***/ "./public/app/core/directives/autofill_event_fix.ts":
/*!**********************************************************!*\
  !*** ./public/app/core/directives/autofill_event_fix.ts ***!
  \**********************************************************/
/*! exports provided: autofillEventFix */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autofillEventFix", function() { return autofillEventFix; });
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");

/** @ngInject */
function autofillEventFix($compile) {
    return {
        link: function ($scope, elem) {
            var input = elem[0];
            var dispatchChangeEvent = function () {
                var event = new Event('change');
                return input.dispatchEvent(event);
            };
            var onAnimationStart = function (_a) {
                var animationName = _a.animationName;
                switch (animationName) {
                    case 'onAutoFillStart':
                        return dispatchChangeEvent();
                    case 'onAutoFillCancel':
                        return dispatchChangeEvent();
                }
                return null;
            };
            // const onChange = (evt: Event) => console.log(evt);
            input.addEventListener('animationstart', onAnimationStart);
            // input.addEventListener('change', onChange);
            $scope.$on('$destroy', function () {
                input.removeEventListener('animationstart', onAnimationStart);
                // input.removeEventListener('change', onChange);
            });
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('autofillEventFix', autofillEventFix);


/***/ }),

/***/ "./public/app/core/directives/diff-view.ts":
/*!*************************************************!*\
  !*** ./public/app/core/directives/diff-view.ts ***!
  \*************************************************/
/*! exports provided: DeltaCtrl, delta, LinkJSONCtrl, linkJson */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeltaCtrl", function() { return DeltaCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delta", function() { return delta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinkJSONCtrl", function() { return LinkJSONCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linkJson", function() { return linkJson; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


var DeltaCtrl = /** @class */ (function () {
    /** @ngInject */
    function DeltaCtrl($rootScope) {
        var _this = this;
        this.$rootScope = $rootScope;
        var waitForCompile = function (mutations) {
            if (mutations.length === 1) {
                _this.$rootScope.appEvent('json-diff-ready');
            }
        };
        this.observer = new MutationObserver(waitForCompile);
        var observerConfig = {
            attributes: true,
            attributeFilter: ['class'],
            characterData: false,
            childList: true,
            subtree: false,
        };
        this.observer.observe(angular__WEBPACK_IMPORTED_MODULE_0___default.a.element('.delta-html')[0], observerConfig);
    }
    DeltaCtrl.prototype.$onDestroy = function () {
        this.observer.disconnect();
    };
    return DeltaCtrl;
}());

function delta() {
    return {
        controller: DeltaCtrl,
        replace: false,
        restrict: 'A',
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('diffDelta', delta);
// Link to JSON line number
var LinkJSONCtrl = /** @class */ (function () {
    /** @ngInject */
    function LinkJSONCtrl($scope, $rootScope, $anchorScroll) {
        this.$scope = $scope;
        this.$rootScope = $rootScope;
        this.$anchorScroll = $anchorScroll;
    }
    LinkJSONCtrl.prototype.goToLine = function (line) {
        var _this = this;
        var unbind;
        var scroll = function () {
            _this.$anchorScroll("l" + line);
            unbind();
        };
        this.$scope.switchView().then(function () {
            unbind = _this.$rootScope.$on('json-diff-ready', scroll.bind(_this));
        });
    };
    return LinkJSONCtrl;
}());

function linkJson() {
    return {
        controller: LinkJSONCtrl,
        controllerAs: 'ctrl',
        replace: true,
        restrict: 'E',
        scope: {
            line: '@lineDisplay',
            link: '@lineLink',
            switchView: '&',
        },
        template: "<a class=\"diff-linenum btn btn-inverse btn-small\" ng-click=\"ctrl.goToLine(link)\">Line {{ line }}</a>",
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('diffLinkJson', linkJson);


/***/ }),

/***/ "./public/app/core/directives/dropdown_typeahead.ts":
/*!**********************************************************!*\
  !*** ./public/app/core/directives/dropdown_typeahead.ts ***!
  \**********************************************************/
/*! exports provided: dropdownTypeahead, dropdownTypeahead2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dropdownTypeahead", function() { return dropdownTypeahead; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dropdownTypeahead2", function() { return dropdownTypeahead2; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");



/** @ngInject */
function dropdownTypeahead($compile) {
    var inputTemplate = '<input type="text"' +
        ' class="gf-form-input input-medium tight-form-input"' +
        ' spellcheck="false" style="display:none"></input>';
    var buttonTemplate = '<a class="gf-form-label tight-form-func dropdown-toggle"' +
        ' tabindex="1" gf-dropdown="menuItems" data-toggle="dropdown"' +
        ' ><i class="fa fa-plus"></i></a>';
    return {
        scope: {
            menuItems: '=dropdownTypeahead',
            dropdownTypeaheadOnSelect: '&dropdownTypeaheadOnSelect',
            model: '=ngModel',
        },
        link: function ($scope, elem, attrs) {
            var $input = jquery__WEBPACK_IMPORTED_MODULE_1___default()(inputTemplate);
            var $button = jquery__WEBPACK_IMPORTED_MODULE_1___default()(buttonTemplate);
            $input.appendTo(elem);
            $button.appendTo(elem);
            if (attrs.linkText) {
                $button.html(attrs.linkText);
            }
            if (attrs.ngModel) {
                $scope.$watch('model', function (newValue) {
                    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each($scope.menuItems, function (item) {
                        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(item.submenu, function (subItem) {
                            if (subItem.value === newValue) {
                                $button.html(subItem.text);
                            }
                        });
                    });
                });
            }
            var typeaheadValues = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.reduce($scope.menuItems, function (memo, value, index) {
                if (!value.submenu) {
                    value.click = 'menuItemSelected(' + index + ')';
                    memo.push(value.text);
                }
                else {
                    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(value.submenu, function (item, subIndex) {
                        item.click = 'menuItemSelected(' + index + ',' + subIndex + ')';
                        memo.push(value.text + ' ' + item.text);
                    });
                }
                return memo;
            }, []);
            var closeDropdownMenu = function () {
                $input.hide();
                $input.val('');
                $button.show();
                $button.focus();
                elem.removeClass('open');
            };
            $scope.menuItemSelected = function (index, subIndex) {
                var menuItem = $scope.menuItems[index];
                var payload = { $item: menuItem };
                if (menuItem.submenu && subIndex !== void 0) {
                    payload.$subItem = menuItem.submenu[subIndex];
                }
                $scope.dropdownTypeaheadOnSelect(payload);
                closeDropdownMenu();
            };
            $input.attr('data-provide', 'typeahead');
            $input.typeahead({
                source: typeaheadValues,
                minLength: 1,
                items: 10,
                updater: function (value) {
                    var result = {};
                    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each($scope.menuItems, function (menuItem) {
                        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(menuItem.submenu, function (submenuItem) {
                            if (value === menuItem.text + ' ' + submenuItem.text) {
                                result.$subItem = submenuItem;
                                result.$item = menuItem;
                            }
                        });
                    });
                    if (result.$item) {
                        $scope.$apply(function () {
                            $scope.dropdownTypeaheadOnSelect(result);
                        });
                    }
                    $input.trigger('blur');
                    return '';
                },
            });
            $button.click(function () {
                $button.hide();
                $input.show();
                $input.focus();
            });
            $input.keyup(function () {
                elem.toggleClass('open', $input.val() === '');
            });
            elem.mousedown(function (evt) {
                evt.preventDefault();
            });
            $input.blur(function () {
                $input.hide();
                $input.val('');
                $button.show();
                $button.focus();
                // clicking the function dropdown menu won't
                // work if you remove class at once
                setTimeout(function () {
                    elem.removeClass('open');
                }, 200);
            });
            $compile(elem.contents())($scope);
        },
    };
}
/** @ngInject */
function dropdownTypeahead2($compile) {
    var inputTemplate = '<input type="text"' + ' class="gf-form-input"' + ' spellcheck="false" style="display:none"></input>';
    var buttonTemplate = '<a class="{{buttonTemplateClass}} dropdown-toggle"' +
        ' tabindex="1" gf-dropdown="menuItems" data-toggle="dropdown"' +
        ' ><i class="fa fa-plus"></i></a>';
    return {
        scope: {
            menuItems: '=dropdownTypeahead2',
            dropdownTypeaheadOnSelect: '&dropdownTypeaheadOnSelect',
            model: '=ngModel',
            buttonTemplateClass: '@',
        },
        link: function ($scope, elem, attrs) {
            var $input = jquery__WEBPACK_IMPORTED_MODULE_1___default()(inputTemplate);
            if (!$scope.buttonTemplateClass) {
                $scope.buttonTemplateClass = 'gf-form-input';
            }
            var $button = jquery__WEBPACK_IMPORTED_MODULE_1___default()(buttonTemplate);
            var timeoutId = {
                blur: null,
            };
            $input.appendTo(elem);
            $button.appendTo(elem);
            if (attrs.linkText) {
                $button.html(attrs.linkText);
            }
            if (attrs.ngModel) {
                $scope.$watch('model', function (newValue) {
                    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each($scope.menuItems, function (item) {
                        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(item.submenu, function (subItem) {
                            if (subItem.value === newValue) {
                                $button.html(subItem.text);
                            }
                        });
                    });
                });
            }
            var typeaheadValues = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.reduce($scope.menuItems, function (memo, value, index) {
                if (!value.submenu) {
                    value.click = 'menuItemSelected(' + index + ')';
                    memo.push(value.text);
                }
                else {
                    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(value.submenu, function (item, subIndex) {
                        item.click = 'menuItemSelected(' + index + ',' + subIndex + ')';
                        memo.push(value.text + ' ' + item.text);
                    });
                }
                return memo;
            }, []);
            var closeDropdownMenu = function () {
                $input.hide();
                $input.val('');
                $button.show();
                $button.focus();
                elem.removeClass('open');
            };
            $scope.menuItemSelected = function (index, subIndex) {
                var menuItem = $scope.menuItems[index];
                var payload = { $item: menuItem };
                if (menuItem.submenu && subIndex !== void 0) {
                    payload.$subItem = menuItem.submenu[subIndex];
                }
                $scope.dropdownTypeaheadOnSelect(payload);
                closeDropdownMenu();
            };
            $input.attr('data-provide', 'typeahead');
            $input.typeahead({
                source: typeaheadValues,
                minLength: 1,
                items: 10,
                updater: function (value) {
                    var result = {};
                    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each($scope.menuItems, function (menuItem) {
                        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(menuItem.submenu, function (submenuItem) {
                            if (value === menuItem.text + ' ' + submenuItem.text) {
                                result.$subItem = submenuItem;
                                result.$item = menuItem;
                            }
                        });
                    });
                    if (result.$item) {
                        $scope.$apply(function () {
                            $scope.dropdownTypeaheadOnSelect(result);
                        });
                    }
                    $input.trigger('blur');
                    return '';
                },
            });
            $button.click(function () {
                $button.hide();
                $input.show();
                $input.focus();
            });
            $input.keyup(function () {
                elem.toggleClass('open', $input.val() === '');
            });
            elem.mousedown(function (evt) {
                evt.preventDefault();
                timeoutId.blur = null;
            });
            $input.blur(function () {
                timeoutId.blur = setTimeout(function () {
                    closeDropdownMenu();
                }, 1);
            });
            $compile(elem.contents())($scope);
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('dropdownTypeahead', dropdownTypeahead);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('dropdownTypeahead2', dropdownTypeahead2);


/***/ }),

/***/ "./public/app/core/directives/give_focus.ts":
/*!**************************************************!*\
  !*** ./public/app/core/directives/give_focus.ts ***!
  \**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");

_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('giveFocus', function () {
    return function (scope, element, attrs) {
        element.click(function (e) {
            e.stopPropagation();
        });
        scope.$watch(attrs.giveFocus, function (newValue) {
            if (!newValue) {
                return;
            }
            setTimeout(function () {
                element.focus();
                var domEl = element[0];
                if (domEl.setSelectionRange) {
                    var pos = element.val().length * 2;
                    domEl.setSelectionRange(pos, pos);
                }
            }, 200);
        }, true);
    };
});
/* harmony default export */ __webpack_exports__["default"] = ({});


/***/ }),

/***/ "./public/app/core/directives/metric_segment.ts":
/*!******************************************************!*\
  !*** ./public/app/core/directives/metric_segment.ts ***!
  \******************************************************/
/*! exports provided: metricSegment, metricSegmentModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "metricSegment", function() { return metricSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "metricSegmentModel", function() { return metricSegmentModel; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");



/** @ngInject */
function metricSegment($compile, $sce, templateSrv) {
    var inputTemplate = '<input type="text" data-provide="typeahead" ' +
        ' class="gf-form-input input-medium"' +
        ' spellcheck="false" style="display:none"></input>';
    var linkTemplate = '<a class="gf-form-label" ng-class="segment.cssClass" ' +
        'tabindex="1" give-focus="segment.focus" ng-bind-html="segment.html"></a>';
    var selectTemplate = '<a class="gf-form-input gf-form-input--dropdown" ng-class="segment.cssClass" ' +
        'tabindex="1" give-focus="segment.focus" ng-bind-html="segment.html"></a>';
    return {
        scope: {
            segment: '=',
            getOptions: '&',
            onChange: '&',
            debounce: '@',
        },
        link: function ($scope, elem) {
            var $input = jquery__WEBPACK_IMPORTED_MODULE_1___default()(inputTemplate);
            var segment = $scope.segment;
            var $button = jquery__WEBPACK_IMPORTED_MODULE_1___default()(segment.selectMode ? selectTemplate : linkTemplate);
            var options = null;
            var cancelBlur = null;
            var linkMode = true;
            var debounceLookup = $scope.debounce;
            $input.appendTo(elem);
            $button.appendTo(elem);
            $scope.updateVariableValue = function (value) {
                if (value === '' || segment.value === value) {
                    return;
                }
                $scope.$apply(function () {
                    var selected = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find($scope.altSegments, { value: value });
                    if (selected) {
                        segment.value = selected.value;
                        segment.html = selected.html || $sce.trustAsHtml(templateSrv.highlightVariablesAsHtml(selected.value));
                        segment.fake = false;
                        segment.expandable = selected.expandable;
                        if (selected.type) {
                            segment.type = selected.type;
                        }
                    }
                    else if (segment.custom !== 'false') {
                        segment.value = value;
                        segment.html = $sce.trustAsHtml(templateSrv.highlightVariablesAsHtml(value));
                        segment.expandable = true;
                        segment.fake = false;
                    }
                    $scope.onChange();
                });
            };
            $scope.switchToLink = function (fromClick) {
                if (linkMode && !fromClick) {
                    return;
                }
                clearTimeout(cancelBlur);
                cancelBlur = null;
                linkMode = true;
                $input.hide();
                $button.show();
                $scope.updateVariableValue($input.val());
            };
            $scope.inputBlur = function () {
                // happens long before the click event on the typeahead options
                // need to have long delay because the blur
                cancelBlur = setTimeout($scope.switchToLink, 200);
            };
            $scope.source = function (query, callback) {
                $scope.$apply(function () {
                    $scope.getOptions({ $query: query }).then(function (altSegments) {
                        $scope.altSegments = altSegments;
                        options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map($scope.altSegments, function (alt) {
                            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(alt.value);
                        });
                        // add custom values
                        if (segment.custom !== 'false') {
                            if (!segment.fake && lodash__WEBPACK_IMPORTED_MODULE_0___default.a.indexOf(options, segment.value) === -1) {
                                options.unshift(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(segment.value));
                            }
                        }
                        callback(options);
                    });
                });
            };
            $scope.updater = function (value) {
                value = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.unescape(value);
                if (value === segment.value) {
                    clearTimeout(cancelBlur);
                    $input.focus();
                    return value;
                }
                $input.val(value);
                $scope.switchToLink(true);
                return value;
            };
            $scope.matcher = function (item) {
                if (linkMode) {
                    return false;
                }
                var str = this.query;
                if (str[0] === '/') {
                    str = str.substring(1);
                }
                if (str[str.length - 1] === '/') {
                    str = str.substring(0, str.length - 1);
                }
                try {
                    return item.toLowerCase().match(str.toLowerCase());
                }
                catch (e) {
                    return false;
                }
            };
            $input.attr('data-provide', 'typeahead');
            $input.typeahead({
                source: $scope.source,
                minLength: 0,
                items: 10000,
                updater: $scope.updater,
                matcher: $scope.matcher,
            });
            var typeahead = $input.data('typeahead');
            typeahead.lookup = function () {
                this.query = this.$element.val() || '';
                var items = this.source(this.query, jquery__WEBPACK_IMPORTED_MODULE_1___default.a.proxy(this.process, this));
                return items ? this.process(items) : items;
            };
            if (debounceLookup) {
                typeahead.lookup = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.debounce(typeahead.lookup, 500, { leading: true });
            }
            $button.keydown(function (evt) {
                // trigger typeahead on down arrow or enter key
                if (evt.keyCode === 40 || evt.keyCode === 13) {
                    $button.click();
                }
            });
            $button.click(function () {
                options = null;
                $input.css('width', Math.max($button.width(), 80) + 16 + 'px');
                $button.hide();
                $input.show();
                $input.focus();
                linkMode = false;
                var typeahead = $input.data('typeahead');
                if (typeahead) {
                    $input.val('');
                    typeahead.lookup();
                }
            });
            $input.blur($scope.inputBlur);
            $compile(elem.contents())($scope);
        },
    };
}
/** @ngInject */
function metricSegmentModel(uiSegmentSrv, $q) {
    return {
        template: '<metric-segment segment="segment" get-options="getOptionsInternal()" on-change="onSegmentChange()"></metric-segment>',
        restrict: 'E',
        scope: {
            property: '=',
            options: '=',
            getOptions: '&',
            onChange: '&',
        },
        link: {
            pre: function postLink($scope, elem, attrs) {
                var cachedOptions;
                $scope.valueToSegment = function (value) {
                    var option = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find($scope.options, { value: value });
                    var segment = {
                        cssClass: attrs.cssClass,
                        custom: attrs.custom,
                        value: option ? option.text : value,
                        selectMode: attrs.selectMode,
                    };
                    return uiSegmentSrv.newSegment(segment);
                };
                $scope.getOptionsInternal = function () {
                    if ($scope.options) {
                        cachedOptions = $scope.options;
                        return $q.when(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map($scope.options, function (option) {
                            return { value: option.text };
                        }));
                    }
                    else {
                        return $scope.getOptions().then(function (options) {
                            cachedOptions = options;
                            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(options, function (option) {
                                if (option.html) {
                                    return option;
                                }
                                return { value: option.text };
                            });
                        });
                    }
                };
                $scope.onSegmentChange = function () {
                    if (cachedOptions) {
                        var option = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(cachedOptions, { text: $scope.segment.value });
                        if (option && option.value !== $scope.property) {
                            $scope.property = option.value;
                        }
                        else if (attrs.custom !== 'false') {
                            $scope.property = $scope.segment.value;
                        }
                    }
                    else {
                        $scope.property = $scope.segment.value;
                    }
                    // needs to call this after digest so
                    // property is synced with outerscope
                    $scope.$$postDigest(function () {
                        $scope.$apply(function () {
                            $scope.onChange();
                        });
                    });
                };
                $scope.segment = $scope.valueToSegment($scope.property);
            },
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('metricSegment', metricSegment);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('metricSegmentModel', metricSegmentModel);


/***/ }),

/***/ "./public/app/core/directives/misc.ts":
/*!********************************************!*\
  !*** ./public/app/core/directives/misc.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var clipboard__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! clipboard */ "./node_modules/clipboard/dist/clipboard.js");
/* harmony import */ var clipboard__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(clipboard__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");





/** @ngInject */
function tip($compile) {
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            var _t = '<i class="grafana-tip fa fa-' +
                (attrs.icon || 'question-circle') +
                '" bs-tooltip="\'' +
                app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__["default"].addslashes(elem.text()) +
                '\'"></i>';
            _t = _t.replace(/{/g, '\\{').replace(/}/g, '\\}');
            elem.replaceWith($compile(angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(_t))(scope));
        },
    };
}
function clipboardButton() {
    return {
        scope: {
            getText: '&clipboardButton',
        },
        link: function (scope, elem) {
            scope.clipboard = new clipboard__WEBPACK_IMPORTED_MODULE_1___default.a(elem[0], {
                text: function () {
                    return scope.getText();
                },
            });
            scope.clipboard.on('success', function () {
                app_core_core__WEBPACK_IMPORTED_MODULE_4__["appEvents"].emit('alert-success', ['Content copied to clipboard']);
            });
            scope.$on('$destroy', function () {
                if (scope.clipboard) {
                    scope.clipboard.destroy();
                }
            });
        },
    };
}
/** @ngInject */
function compile($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(function (scope) {
                return scope.$eval(attrs.compile);
            }, function (value) {
                element.html(value);
                $compile(element.contents())(scope);
            });
        },
    };
}
function watchChange() {
    return {
        scope: { onchange: '&watchChange' },
        link: function (scope, element) {
            element.on('input', function () {
                scope.$apply(function () {
                    scope.onchange({ inputValue: element.val() });
                });
            });
        },
    };
}
/** @ngInject */
function editorOptBool($compile) {
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : '';
            var tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : '';
            var showIf = attrs.showIf ? ' ng-show="' + attrs.showIf + '" ' : '';
            var template = '<div class="editor-option gf-form-checkbox text-center"' +
                showIf +
                '>' +
                ' <label for="' +
                attrs.model +
                '" class="small">' +
                attrs.text +
                tip +
                '</label>' +
                '<input class="cr1" id="' +
                attrs.model +
                '" type="checkbox" ' +
                '       ng-model="' +
                attrs.model +
                '"' +
                ngchange +
                '       ng-checked="' +
                attrs.model +
                '"></input>' +
                ' <label for="' +
                attrs.model +
                '" class="cr1"></label>';
            elem.replaceWith($compile(angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(template))(scope));
        },
    };
}
/** @ngInject */
function editorCheckbox($compile, $interpolate) {
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            var text = $interpolate(attrs.text)(scope);
            var model = $interpolate(attrs.model)(scope);
            var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : '';
            var tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : '';
            var label = '<label for="' + scope.$id + model + '" class="checkbox-label">' + text + tip + '</label>';
            var template = '<input class="cr1" id="' +
                scope.$id +
                model +
                '" type="checkbox" ' +
                '       ng-model="' +
                model +
                '"' +
                ngchange +
                '       ng-checked="' +
                model +
                '"></input>' +
                ' <label for="' +
                scope.$id +
                model +
                '" class="cr1"></label>';
            template = template + label;
            elem.addClass('gf-form-checkbox');
            elem.html($compile(angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(template))(scope));
        },
    };
}
/** @ngInject */
function gfDropdown($parse, $compile, $timeout) {
    function buildTemplate(items, placement) {
        var upclass = placement === 'top' ? 'dropup' : '';
        var ul = ['<ul class="dropdown-menu ' + upclass + '" role="menu" aria-labelledby="drop1">', '</ul>'];
        for (var index = 0; index < items.length; index++) {
            var item = items[index];
            if (item.divider) {
                ul.splice(index + 1, 0, '<li class="divider"></li>');
                continue;
            }
            var li = '<li' +
                (item.submenu && item.submenu.length ? ' class="dropdown-submenu"' : '') +
                '>' +
                '<a tabindex="-1" ng-href="' +
                (item.href || '') +
                '"' +
                (item.click ? ' ng-click="' + item.click + '"' : '') +
                (item.target ? ' target="' + item.target + '"' : '') +
                (item.method ? ' data-method="' + item.method + '"' : '') +
                '>' +
                (item.text || '') +
                '</a>';
            if (item.submenu && item.submenu.length) {
                li += buildTemplate(item.submenu).join('\n');
            }
            li += '</li>';
            ul.splice(index + 1, 0, li);
        }
        return ul;
    }
    return {
        restrict: 'EA',
        scope: true,
        link: function postLink(scope, iElement, iAttrs) {
            var getter = $parse(iAttrs.gfDropdown), items = getter(scope);
            $timeout(function () {
                var placement = iElement.data('placement');
                var dropdown = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(buildTemplate(items, placement).join(''));
                dropdown.insertAfter(iElement);
                $compile(iElement.next('ul.dropdown-menu'))(scope);
            });
            iElement.addClass('dropdown-toggle').attr('data-toggle', 'dropdown');
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('tip', tip);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('clipboardButton', clipboardButton);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('compile', compile);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('watchChange', watchChange);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('editorOptBool', editorOptBool);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('editorCheckbox', editorCheckbox);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('gfDropdown', gfDropdown);


/***/ }),

/***/ "./public/app/core/directives/ng_model_on_blur.ts":
/*!********************************************************!*\
  !*** ./public/app/core/directives/ng_model_on_blur.ts ***!
  \********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");


function ngModelOnBlur() {
    return {
        restrict: 'A',
        priority: 1,
        require: 'ngModel',
        link: function (scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') {
                return;
            }
            elm.off('input keydown change');
            elm.bind('blur', function () {
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(elm.val());
                });
            });
        },
    };
}
function emptyToNull() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.push(function (viewValue) {
                if (viewValue === '') {
                    return null;
                }
                return viewValue;
            });
        },
    };
}
function validTimeSpan() {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$validators.integer = function (modelValue, viewValue) {
                if (ctrl.$isEmpty(modelValue)) {
                    return true;
                }
                if (viewValue.indexOf('$') === 0 || viewValue.indexOf('+$') === 0) {
                    return true; // allow template variable
                }
                var info = _grafana_data__WEBPACK_IMPORTED_MODULE_1__["rangeUtil"].describeTextRange(viewValue);
                return info.invalid !== true;
            };
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('ngModelOnblur', ngModelOnBlur);
_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('emptyToNull', emptyToNull);
_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('validTimeSpan', validTimeSpan);


/***/ }),

/***/ "./public/app/core/directives/rebuild_on_change.ts":
/*!*********************************************************!*\
  !*** ./public/app/core/directives/rebuild_on_change.ts ***!
  \*********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


function getBlockNodes(nodes) {
    var node = nodes[0];
    var endNode = nodes[nodes.length - 1];
    var blockNodes;
    node = node.nextSibling;
    for (var i = 1; node !== endNode && node; i++) {
        if (blockNodes || nodes[i] !== node) {
            if (!blockNodes) {
                blockNodes = jquery__WEBPACK_IMPORTED_MODULE_0___default()([].slice.call(nodes, 0, i));
            }
            blockNodes.push(node);
        }
        node = node.nextSibling;
    }
    return blockNodes || nodes;
}
/** @ngInject */
function rebuildOnChange($animate) {
    return {
        multiElement: true,
        terminal: true,
        transclude: true,
        priority: 600,
        restrict: 'E',
        link: function (scope, elem, attrs, ctrl, transclude) {
            var block, childScope, previousElements;
            function cleanUp() {
                if (previousElements) {
                    previousElements.remove();
                    previousElements = null;
                }
                if (childScope) {
                    childScope.$destroy();
                    childScope = null;
                }
                if (block) {
                    previousElements = getBlockNodes(block.clone);
                    $animate.leave(previousElements).then(function () {
                        previousElements = null;
                    });
                    block = null;
                }
            }
            scope.$watch(attrs.property, function rebuildOnChangeAction(value, oldValue) {
                if (childScope && value !== oldValue) {
                    cleanUp();
                }
                if (!childScope && (value || attrs.showNull)) {
                    transclude(function (clone, newScope) {
                        childScope = newScope;
                        clone[clone.length++] = document.createComment(' end rebuild on change ');
                        block = { clone: clone };
                        $animate.enter(clone, elem.parent(), elem);
                    });
                }
                else {
                    cleanUp();
                }
            });
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('rebuildOnChange', rebuildOnChange);


/***/ }),

/***/ "./public/app/core/directives/tags.ts":
/*!********************************************!*\
  !*** ./public/app/core/directives/tags.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_utils_tags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/tags */ "./public/app/core/utils/tags.ts");
/* harmony import */ var vendor_tagsinput_bootstrap_tagsinput_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! vendor/tagsinput/bootstrap-tagsinput.js */ "./public/vendor/tagsinput/bootstrap-tagsinput.js");
/* harmony import */ var vendor_tagsinput_bootstrap_tagsinput_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(vendor_tagsinput_bootstrap_tagsinput_js__WEBPACK_IMPORTED_MODULE_4__);





function setColor(name, element) {
    var _a = app_core_utils_tags__WEBPACK_IMPORTED_MODULE_3__["default"].getTagColorsFromName(name), color = _a.color, borderColor = _a.borderColor;
    element.css('background-color', color);
    element.css('border-color', borderColor);
}
function tagColorFromName() {
    return {
        scope: { tagColorFromName: '=' },
        link: function (scope, element) {
            setColor(scope.tagColorFromName, element);
        },
    };
}
function bootstrapTagsinput() {
    function getItemProperty(scope, property) {
        if (!property) {
            return undefined;
        }
        if (angular__WEBPACK_IMPORTED_MODULE_0___default.a.isFunction(scope.$parent[property])) {
            return scope.$parent[property];
        }
        return function (item) {
            return item[property];
        };
    }
    return {
        restrict: 'EA',
        scope: {
            model: '=ngModel',
            onTagsUpdated: '&',
        },
        template: '<select multiple></select>',
        replace: false,
        link: function (scope, element, attrs) {
            var _this = this;
            if (!angular__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(scope.model)) {
                scope.model = [];
            }
            var select = jquery__WEBPACK_IMPORTED_MODULE_1___default()('select', element);
            if (attrs.placeholder) {
                select.attr('placeholder', attrs.placeholder);
            }
            select.tagsinput({
                typeahead: {
                    source: angular__WEBPACK_IMPORTED_MODULE_0___default.a.isFunction(scope.$parent[attrs.typeaheadSource])
                        ? scope.$parent[attrs.typeaheadSource]
                        : null,
                },
                widthClass: attrs.widthClass,
                itemValue: getItemProperty(scope, attrs.itemvalue),
                itemText: getItemProperty(scope, attrs.itemtext),
                tagClass: angular__WEBPACK_IMPORTED_MODULE_0___default.a.isFunction(scope.$parent[attrs.tagclass])
                    ? scope.$parent[attrs.tagclass]
                    : function () {
                        return attrs.tagclass;
                    },
            });
            select.on('itemAdded', function (event) {
                if (scope.model.indexOf(event.item) === -1) {
                    scope.model.push(event.item);
                    if (scope.onTagsUpdated) {
                        scope.onTagsUpdated();
                    }
                }
                var tagElement = select
                    .next()
                    .children('span')
                    .filter(function () {
                    return jquery__WEBPACK_IMPORTED_MODULE_1___default()(_this).text() === event.item;
                });
                setColor(event.item, tagElement);
            });
            select.on('itemRemoved', function (event) {
                var idx = scope.model.indexOf(event.item);
                if (idx !== -1) {
                    scope.model.splice(idx, 1);
                    if (scope.onTagsUpdated) {
                        scope.onTagsUpdated();
                    }
                }
            });
            scope.$watch('model', function () {
                if (!angular__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(scope.model)) {
                    scope.model = [];
                }
                select.tagsinput('removeAll');
                for (var i = 0; i < scope.model.length; i++) {
                    select.tagsinput('add', scope.model[i]);
                }
            }, true);
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('tagColorFromName', tagColorFromName);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('bootstrapTagsinput', bootstrapTagsinput);


/***/ }),

/***/ "./public/app/core/directives/value_select_dropdown.ts":
/*!*************************************************************!*\
  !*** ./public/app/core/directives/value_select_dropdown.ts ***!
  \*************************************************************/
/*! exports provided: ValueSelectDropdownCtrl, valueSelectDropdown */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueSelectDropdownCtrl", function() { return ValueSelectDropdownCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueSelectDropdown", function() { return valueSelectDropdown; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");



var ValueSelectDropdownCtrl = /** @class */ (function () {
    /** @ngInject */
    function ValueSelectDropdownCtrl($q) {
        this.$q = $q;
    }
    ValueSelectDropdownCtrl.prototype.show = function () {
        var _this = this;
        this.oldVariableText = this.variable.current.text;
        this.highlightIndex = -1;
        this.options = this.variable.options;
        this.selectedValues = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.options, { selected: true });
        this.tags = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.variable.tags, function (value) {
            var tag = { text: value, selected: false };
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(_this.variable.current.tags, function (tagObj) {
                if (tagObj.text === value) {
                    tag = tagObj;
                }
            });
            return tag;
        });
        this.search = {
            query: '',
            options: this.options.slice(0, Math.min(this.options.length, 1000)),
        };
        this.dropdownVisible = true;
    };
    ValueSelectDropdownCtrl.prototype.updateLinkText = function () {
        var current = this.variable.current;
        if (current.tags && current.tags.length) {
            // filer out values that are in selected tags
            var selectedAndNotInTag = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.variable.options, function (option) {
                if (!option.selected) {
                    return false;
                }
                for (var i = 0; i < current.tags.length; i++) {
                    var tag = current.tags[i];
                    if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(tag.values, option.value) !== -1) {
                        return false;
                    }
                }
                return true;
            });
            // convert values to text
            var currentTexts = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(selectedAndNotInTag, 'text');
            // join texts
            this.linkText = currentTexts.join(' + ');
            if (this.linkText.length > 0) {
                this.linkText += ' + ';
            }
        }
        else {
            this.linkText = this.variable.current.text;
        }
    };
    ValueSelectDropdownCtrl.prototype.clearSelections = function () {
        this.selectedValues = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.options, { selected: true });
        if (this.selectedValues.length) {
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(this.options, function (option) {
                option.selected = false;
            });
        }
        else {
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(this.search.options, function (option) {
                option.selected = true;
            });
        }
        this.selectionsChanged(false);
    };
    ValueSelectDropdownCtrl.prototype.selectTag = function (tag) {
        var _this = this;
        tag.selected = !tag.selected;
        var tagValuesPromise;
        if (!tag.values) {
            tagValuesPromise = this.variable.getValuesForTag(tag.text);
        }
        else {
            tagValuesPromise = this.$q.when(tag.values);
        }
        return tagValuesPromise.then(function (values) {
            tag.values = values;
            tag.valuesText = values.join(' + ');
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(_this.options, function (option) {
                if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(tag.values, option.value) !== -1) {
                    option.selected = tag.selected;
                }
            });
            _this.selectionsChanged(false);
        });
    };
    ValueSelectDropdownCtrl.prototype.keyDown = function (evt) {
        if (evt.keyCode === 27) {
            this.hide();
        }
        if (evt.keyCode === 40) {
            this.moveHighlight(1);
        }
        if (evt.keyCode === 38) {
            this.moveHighlight(-1);
        }
        if (evt.keyCode === 13) {
            if (this.search.options.length === 0) {
                this.commitChanges();
            }
            else {
                this.selectValue(this.search.options[this.highlightIndex], {}, true, false);
            }
        }
        if (evt.keyCode === 32) {
            this.selectValue(this.search.options[this.highlightIndex], {}, false, false);
        }
    };
    ValueSelectDropdownCtrl.prototype.moveHighlight = function (direction) {
        this.highlightIndex = (this.highlightIndex + direction) % this.search.options.length;
    };
    ValueSelectDropdownCtrl.prototype.selectValue = function (option, event, commitChange, excludeOthers) {
        var _this = this;
        if (!option) {
            return;
        }
        option.selected = this.variable.multi ? !option.selected : true;
        commitChange = commitChange || false;
        excludeOthers = excludeOthers || false;
        var setAllExceptCurrentTo = function (newValue) {
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(_this.options, function (other) {
                if (option !== other) {
                    other.selected = newValue;
                }
            });
        };
        // commit action (enter key), should not deselect it
        if (commitChange) {
            option.selected = true;
        }
        if (option.text === 'All' || excludeOthers) {
            setAllExceptCurrentTo(false);
            commitChange = true;
        }
        else if (!this.variable.multi) {
            setAllExceptCurrentTo(false);
            commitChange = true;
        }
        else if (event.ctrlKey || event.metaKey || event.shiftKey) {
            commitChange = true;
            setAllExceptCurrentTo(false);
        }
        this.selectionsChanged(commitChange);
    };
    ValueSelectDropdownCtrl.prototype.selectionsChanged = function (commitChange) {
        var _this = this;
        this.selectedValues = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.options, { selected: true });
        if (this.selectedValues.length > 1) {
            if (this.selectedValues[0].text === 'All') {
                this.selectedValues[0].selected = false;
                this.selectedValues = this.selectedValues.slice(1, this.selectedValues.length);
            }
        }
        // validate selected tags
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(this.tags, function (tag) {
            if (tag.selected) {
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(tag.values, function (value) {
                    if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(_this.selectedValues, { value: value })) {
                        tag.selected = false;
                    }
                });
            }
        });
        this.selectedTags = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.tags, { selected: true });
        this.variable.current.value = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.selectedValues, 'value');
        this.variable.current.text = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.selectedValues, 'text').join(' + ');
        this.variable.current.tags = this.selectedTags;
        if (!this.variable.multi) {
            this.variable.current.value = this.selectedValues[0].value;
        }
        if (commitChange) {
            this.commitChanges();
        }
    };
    ValueSelectDropdownCtrl.prototype.commitChanges = function () {
        // if we have a search query and no options use that
        if (this.search.options.length === 0 && this.search.query.length > 0) {
            this.variable.current = { text: this.search.query, value: this.search.query };
        }
        else if (this.selectedValues.length === 0) {
            // make sure one option is selected
            this.options[0].selected = true;
            this.selectionsChanged(false);
        }
        this.dropdownVisible = false;
        this.updateLinkText();
        if (this.variable.current.text !== this.oldVariableText) {
            this.onUpdated();
        }
    };
    ValueSelectDropdownCtrl.prototype.queryChanged = function () {
        var _this = this;
        this.highlightIndex = -1;
        this.search.options = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.options, function (option) {
            return option.text.toLowerCase().indexOf(_this.search.query.toLowerCase()) !== -1;
        });
        this.search.options = this.search.options.slice(0, Math.min(this.search.options.length, 1000));
    };
    ValueSelectDropdownCtrl.prototype.init = function () {
        this.selectedTags = this.variable.current.tags || [];
        this.updateLinkText();
    };
    return ValueSelectDropdownCtrl;
}());

/** @ngInject */
function valueSelectDropdown($compile, $window, $timeout, $rootScope) {
    return {
        scope: { dashboard: '=', variable: '=', onUpdated: '&' },
        templateUrl: 'public/app/partials/valueSelectDropdown.html',
        controller: 'ValueSelectDropdownCtrl',
        controllerAs: 'vm',
        bindToController: true,
        link: function (scope, elem) {
            var bodyEl = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element($window.document.body);
            var linkEl = elem.find('.variable-value-link');
            var inputEl = elem.find('input');
            function openDropdown() {
                inputEl.css('width', Math.max(linkEl.width(), 80) + 'px');
                inputEl.show();
                linkEl.hide();
                inputEl.focus();
                $timeout(function () {
                    bodyEl.on('click', bodyOnClick);
                }, 0, false);
            }
            function switchToLink() {
                inputEl.hide();
                linkEl.show();
                bodyEl.off('click', bodyOnClick);
            }
            function bodyOnClick(e) {
                if (elem.has(e.target).length === 0) {
                    scope.$apply(function () {
                        scope.vm.commitChanges();
                    });
                }
            }
            scope.$watch('vm.dropdownVisible', function (newValue) {
                if (newValue) {
                    openDropdown();
                }
                else {
                    switchToLink();
                }
            });
            scope.vm.dashboard.on('template-variable-value-updated', function () {
                scope.vm.updateLinkText();
            }, scope);
            scope.vm.init();
        },
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].controller('ValueSelectDropdownCtrl', ValueSelectDropdownCtrl);
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('valueSelectDropdown', valueSelectDropdown);


/***/ }),

/***/ "./public/app/core/filters/filters.ts":
/*!********************************************!*\
  !*** ./public/app/core/filters/filters.ts ***!
  \********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].filter('stringSort', function () {
    return function (input) {
        return input.sort();
    };
});
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].filter('slice', function () {
    return function (arr, start, end) {
        if (!lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isUndefined(arr)) {
            return arr.slice(start, end);
        }
        return arr;
    };
});
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].filter('stringify', function () {
    return function (arr) {
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isObject(arr) && !lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(arr)) {
            return angular__WEBPACK_IMPORTED_MODULE_1___default.a.toJson(arr);
        }
        else {
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNull(arr) ? null : arr.toString();
        }
    };
});
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].filter('moment', function () {
    return function (date, mode) {
        switch (mode) {
            case 'ago':
                return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(date).fromNow();
        }
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(date).fromNow();
    };
});
/** @ngInject */
function interpolateTemplateVars(templateSrv) {
    var filterFunc = function (text, scope) {
        var scopedVars;
        if (scope.ctrl) {
            scopedVars = (scope.ctrl.panel || scope.ctrl.row).scopedVars;
        }
        else {
            scopedVars = scope.row.scopedVars;
        }
        return templateSrv.replaceWithText(text, scopedVars);
    };
    filterFunc.$stateful = true;
    return filterFunc;
}
_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].filter('interpolateTemplateVars', interpolateTemplateVars);
/* harmony default export */ __webpack_exports__["default"] = ({});


/***/ }),

/***/ "./public/app/core/hooks/useRefMounted.ts":
/*!************************************************!*\
  !*** ./public/app/core/hooks/useRefMounted.ts ***!
  \************************************************/
/*! exports provided: useRefMounted */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "useRefMounted", function() { return useRefMounted; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var useRefMounted = function () {
    var refMounted = Object(react__WEBPACK_IMPORTED_MODULE_0__["useRef"])(false);
    Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(function () {
        refMounted.current = true;
        return function () {
            refMounted.current = false;
        };
    });
    return refMounted;
};


/***/ }),

/***/ "./public/app/core/jquery_extended.ts":
/*!********************************************!*\
  !*** ./public/app/core/jquery_extended.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);



var $win = jquery__WEBPACK_IMPORTED_MODULE_0___default()(window);
jquery__WEBPACK_IMPORTED_MODULE_0___default.a.fn.place_tt = (function () {
    var defaults = {
        offset: 5,
    };
    return function (x, y, opts) {
        var _this = this;
        opts = jquery__WEBPACK_IMPORTED_MODULE_0___default.a.extend(true, {}, defaults, opts);
        return this.each(function () {
            var $tooltip = jquery__WEBPACK_IMPORTED_MODULE_0___default()(_this);
            var width, height;
            $tooltip.addClass('grafana-tooltip');
            jquery__WEBPACK_IMPORTED_MODULE_0___default()('#tooltip').remove();
            $tooltip.appendTo(document.body);
            if (opts.compile) {
                angular__WEBPACK_IMPORTED_MODULE_1___default.a
                    .element(document)
                    .injector()
                    .invoke([
                    '$compile',
                    '$rootScope',
                    function ($compile, $rootScope) {
                        var tmpScope = $rootScope.$new(true);
                        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.extend(tmpScope, opts.scopeData);
                        $compile($tooltip)(tmpScope);
                        tmpScope.$digest();
                        tmpScope.$destroy();
                    },
                ]);
            }
            width = $tooltip.outerWidth(true);
            height = $tooltip.outerHeight(true);
            $tooltip.css('left', x + opts.offset + width > $win.width() ? x - opts.offset - width : x + opts.offset);
            $tooltip.css('top', y + opts.offset + height > $win.height() ? y - opts.offset - height : y + opts.offset);
        });
    };
})();


/***/ }),

/***/ "./public/app/core/live/live_srv.ts":
/*!******************************************!*\
  !*** ./public/app/core/live/live_srv.ts ***!
  \******************************************/
/*! exports provided: LiveSrv, liveSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LiveSrv", function() { return LiveSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "liveSrv", function() { return instance; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm5/index.js");



var LiveSrv = /** @class */ (function () {
    function LiveSrv() {
        this.observers = {};
    }
    LiveSrv.prototype.getWebSocketUrl = function () {
        var l = window.location;
        return (l.protocol === 'https:' ? 'wss://' : 'ws://') + l.host + app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/ws';
    };
    LiveSrv.prototype.getConnection = function () {
        var _this = this;
        if (this.initPromise) {
            return this.initPromise;
        }
        if (this.conn && this.conn.readyState === 1) {
            return Promise.resolve(this.conn);
        }
        this.initPromise = new Promise(function (resolve, reject) {
            console.log('Live: connecting...');
            _this.conn = new WebSocket(_this.getWebSocketUrl());
            _this.conn.onclose = function (evt) {
                console.log('Live: websocket onclose', evt);
                reject({ message: 'Connection closed' });
                _this.initPromise = null;
                setTimeout(_this.reconnect.bind(_this), 2000);
            };
            _this.conn.onmessage = function (evt) {
                _this.handleMessage(evt.data);
            };
            _this.conn.onerror = function (evt) {
                _this.initPromise = null;
                reject({ message: 'Connection error' });
                console.log('Live: websocket error', evt);
            };
            _this.conn.onopen = function (evt) {
                console.log('opened');
                _this.initPromise = null;
                resolve(_this.conn);
            };
        });
        return this.initPromise;
    };
    LiveSrv.prototype.handleMessage = function (message) {
        message = JSON.parse(message);
        if (!message.stream) {
            console.log('Error: stream message without stream!', message);
            return;
        }
        var observer = this.observers[message.stream];
        if (!observer) {
            this.removeObserver(message.stream, null);
            return;
        }
        observer.next(message);
    };
    LiveSrv.prototype.reconnect = function () {
        var _this = this;
        // no need to reconnect if no one cares
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.keys(this.observers).length === 0) {
            return;
        }
        console.log('LiveSrv: Reconnecting');
        this.getConnection().then(function (conn) {
            lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(_this.observers, function (value, key) {
                _this.send({ action: 'subscribe', stream: key });
            });
        });
    };
    LiveSrv.prototype.send = function (data) {
        this.conn.send(JSON.stringify(data));
    };
    LiveSrv.prototype.addObserver = function (stream, observer) {
        var _this = this;
        this.observers[stream] = observer;
        this.getConnection().then(function (conn) {
            _this.send({ action: 'subscribe', stream: stream });
        });
    };
    LiveSrv.prototype.removeObserver = function (stream, observer) {
        var _this = this;
        console.log('unsubscribe', stream);
        delete this.observers[stream];
        this.getConnection().then(function (conn) {
            _this.send({ action: 'unsubscribe', stream: stream });
        });
    };
    LiveSrv.prototype.subscribe = function (streamName) {
        var _this = this;
        console.log('LiveSrv.subscribe: ' + streamName);
        return rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"].create(function (observer) {
            _this.addObserver(streamName, observer);
            return function () {
                _this.removeObserver(streamName, observer);
            };
        });
        // return this.init().then(() =>  {
        //   this.send({action: 'subscribe', stream: name});
        // });
    };
    return LiveSrv;
}());

var instance = new LiveSrv();



/***/ }),

/***/ "./public/app/core/logs_model.ts":
/*!***************************************!*\
  !*** ./public/app/core/logs_model.ts ***!
  \***************************************/
/*! exports provided: LogLevelColor, dedupLogRows, filterLogLevels, makeSeriesForLogs, dataFrameToLogsModel, logSeriesToLogsModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogLevelColor", function() { return LogLevelColor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dedupLogRows", function() { return dedupLogRows; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterLogLevels", function() { return filterLogLevels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeSeriesForLogs", function() { return makeSeriesForLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataFrameToLogsModel", function() { return dataFrameToLogsModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSeriesToLogsModel", function() { return logSeriesToLogsModel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_utils_colors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/colors */ "./public/app/core/utils/colors.ts");
/* harmony import */ var app_core_utils_text__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/utils/text */ "./public/app/core/utils/text.ts");
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");
/* harmony import */ var app_plugins_panel_graph2_getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/plugins/panel/graph2/getGraphSeriesModel */ "./public/app/plugins/panel/graph2/getGraphSeriesModel.ts");
var _a;








var LogLevelColor = (_a = {},
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].critical] = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["colors"][7],
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].warning] = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["colors"][1],
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].error] = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["colors"][4],
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].info] = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["colors"][0],
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].debug] = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["colors"][5],
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].trace] = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["colors"][2],
    _a[_grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].unknown] = Object(app_core_utils_colors__WEBPACK_IMPORTED_MODULE_4__["getThemeColor"])('#8e8e8e', '#dde4ed'),
    _a);
var isoDateRegexp = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-6]\d[,\.]\d+([+-][0-2]\d:[0-5]\d|Z)/g;
function isDuplicateRow(row, other, strategy) {
    switch (strategy) {
        case _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"].exact:
            // Exact still strips dates
            return row.entry.replace(isoDateRegexp, '') === other.entry.replace(isoDateRegexp, '');
        case _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"].numbers:
            return row.entry.replace(/\d/g, '') === other.entry.replace(/\d/g, '');
        case _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"].signature:
            return row.entry.replace(/\w/g, '') === other.entry.replace(/\w/g, '');
        default:
            return false;
    }
}
function dedupLogRows(logs, strategy) {
    if (strategy === _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"].none) {
        return logs;
    }
    var dedupedRows = logs.rows.reduce(function (result, row, index, list) {
        var rowCopy = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, row);
        var previous = result[result.length - 1];
        if (index > 0 && isDuplicateRow(row, previous, strategy)) {
            previous.duplicates++;
        }
        else {
            rowCopy.duplicates = 0;
            result.push(rowCopy);
        }
        return result;
    }, []);
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, logs, { rows: dedupedRows });
}
function filterLogLevels(logs, hiddenLogLevels) {
    if (hiddenLogLevels.size === 0) {
        return logs;
    }
    var filteredRows = logs.rows.reduce(function (result, row, index, list) {
        if (!hiddenLogLevels.has(row.logLevel)) {
            result.push(row);
        }
        return result;
    }, []);
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, logs, { rows: filteredRows });
}
function makeSeriesForLogs(rows, intervalMs) {
    // currently interval is rangeMs / resolution, which is too low for showing series as bars.
    // need at least 10px per bucket, so we multiply interval by 10. Should be solved higher up the chain
    // when executing queries & interval calculated and not here but this is a temporary fix.
    // intervalMs = intervalMs * 10;
    var e_1, _a, e_2, _b;
    // Graph time series by log level
    var seriesByLevel = {};
    var bucketSize = intervalMs * 10;
    var seriesList = [];
    var sortedRows = rows.sort(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_6__["sortInAscendingOrder"]);
    try {
        for (var sortedRows_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](sortedRows), sortedRows_1_1 = sortedRows_1.next(); !sortedRows_1_1.done; sortedRows_1_1 = sortedRows_1.next()) {
            var row = sortedRows_1_1.value;
            var series = seriesByLevel[row.logLevel];
            if (!series) {
                seriesByLevel[row.logLevel] = series = {
                    lastTs: null,
                    datapoints: [],
                    alias: row.logLevel,
                    color: LogLevelColor[row.logLevel],
                };
                seriesList.push(series);
            }
            // align time to bucket size - used Math.floor for calculation as time of the bucket
            // must be in the past (before Date.now()) to be displayed on the graph
            var time = Math.floor(row.timeEpochMs / bucketSize) * bucketSize;
            // Entry for time
            if (time === series.lastTs) {
                series.datapoints[series.datapoints.length - 1][0]++;
            }
            else {
                series.datapoints.push([1, time]);
                series.lastTs = time;
            }
            try {
                // add zero to other levels to aid stacking so each level series has same number of points
                for (var seriesList_1 = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](seriesList)), seriesList_1_1 = seriesList_1.next(); !seriesList_1_1.done; seriesList_1_1 = seriesList_1.next()) {
                    var other = seriesList_1_1.value;
                    if (other !== series && other.lastTs !== time) {
                        other.datapoints.push([0, time]);
                        other.lastTs = time;
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (seriesList_1_1 && !seriesList_1_1.done && (_b = seriesList_1.return)) _b.call(seriesList_1);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (sortedRows_1_1 && !sortedRows_1_1.done && (_a = sortedRows_1.return)) _a.call(sortedRows_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return seriesList.map(function (series) {
        series.datapoints.sort(function (a, b) {
            return a[1] - b[1];
        });
        // EEEP: converts GraphSeriesXY to DataFrame and back again!
        var data = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toDataFrame"])(series);
        var points = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["getFlotPairs"])({
            xField: data.fields[1],
            yField: data.fields[0],
            nullValueMode: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["NullValueMode"].Null,
        });
        var graphSeries = {
            color: series.color,
            label: series.alias,
            data: points,
            isVisible: true,
            yAxis: {
                index: 1,
                min: 0,
                tickDecimals: 0,
            },
        };
        return graphSeries;
    });
}
function isLogsData(series) {
    return series.fields.some(function (f) { return f.type === _grafana_data__WEBPACK_IMPORTED_MODULE_3__["FieldType"].time; }) && series.fields.some(function (f) { return f.type === _grafana_data__WEBPACK_IMPORTED_MODULE_3__["FieldType"].string; });
}
function dataFrameToLogsModel(dataFrame, intervalMs) {
    var e_3, _a;
    var metricSeries = [];
    var logSeries = [];
    try {
        for (var dataFrame_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dataFrame), dataFrame_1_1 = dataFrame_1.next(); !dataFrame_1_1.done; dataFrame_1_1 = dataFrame_1.next()) {
            var series = dataFrame_1_1.value;
            if (isLogsData(series)) {
                logSeries.push(series);
                continue;
            }
            metricSeries.push(series);
        }
    }
    catch (e_3_1) { e_3 = { error: e_3_1 }; }
    finally {
        try {
            if (dataFrame_1_1 && !dataFrame_1_1.done && (_a = dataFrame_1.return)) _a.call(dataFrame_1);
        }
        finally { if (e_3) throw e_3.error; }
    }
    var logsModel = logSeriesToLogsModel(logSeries);
    if (logsModel) {
        if (metricSeries.length === 0) {
            logsModel.series = makeSeriesForLogs(logsModel.rows, intervalMs);
        }
        else {
            logsModel.series = Object(app_plugins_panel_graph2_getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_7__["getGraphSeriesModel"])(metricSeries, {}, { showBars: true, showLines: false, showPoints: false }, {
                asTable: false,
                isVisible: true,
                placement: 'under',
            });
        }
        return logsModel;
    }
    return {
        hasUniqueLabels: false,
        rows: [],
        meta: [],
        series: [],
    };
}
function logSeriesToLogsModel(logSeries) {
    if (logSeries.length === 0) {
        return undefined;
    }
    var allLabels = [];
    for (var n = 0; n < logSeries.length; n++) {
        var series = logSeries[n];
        if (series.labels) {
            allLabels.push(series.labels);
        }
    }
    var commonLabels = {};
    if (allLabels.length > 0) {
        commonLabels = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["findCommonLabels"])(allLabels);
    }
    var rows = [];
    var hasUniqueLabels = false;
    for (var i = 0; i < logSeries.length; i++) {
        var series = logSeries[i];
        var fieldCache = new _grafana_data__WEBPACK_IMPORTED_MODULE_3__["FieldCache"](series);
        var uniqueLabels = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["findUniqueLabels"])(series.labels, commonLabels);
        if (Object.keys(uniqueLabels).length > 0) {
            hasUniqueLabels = true;
        }
        var timeField = fieldCache.getFirstFieldOfType(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["FieldType"].time);
        var stringField = fieldCache.getFirstFieldOfType(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["FieldType"].string);
        var logLevelField = fieldCache.getFieldByName('level');
        var seriesLogLevel = undefined;
        if (series.labels && Object.keys(series.labels).indexOf('level') !== -1) {
            seriesLogLevel = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["getLogLevelFromKey"])(series.labels['level']);
        }
        for (var j = 0; j < series.length; j++) {
            var ts = timeField.values.get(j);
            var time = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(ts);
            var timeEpochMs = time.valueOf();
            var timeFromNow = time.fromNow();
            var timeLocal = time.format('YYYY-MM-DD HH:mm:ss');
            var timeUtc = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(ts).format('YYYY-MM-DD HH:mm:ss');
            var message = stringField.values.get(j);
            // This should be string but sometimes isn't (eg elastic) because the dataFrame is not strongly typed.
            message = typeof message === 'string' ? message : JSON.stringify(message);
            var logLevel = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogLevel"].unknown;
            if (logLevelField) {
                logLevel = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["getLogLevelFromKey"])(logLevelField.values.get(j));
            }
            else if (seriesLogLevel) {
                logLevel = seriesLogLevel;
            }
            else {
                logLevel = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["getLogLevel"])(message);
            }
            var hasAnsi = Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_5__["hasAnsiCodes"])(message);
            var searchWords = series.meta && series.meta.searchWords ? series.meta.searchWords : [];
            rows.push({
                logLevel: logLevel,
                timeFromNow: timeFromNow,
                timeEpochMs: timeEpochMs,
                timeLocal: timeLocal,
                timeUtc: timeUtc,
                uniqueLabels: uniqueLabels,
                hasAnsi: hasAnsi,
                searchWords: searchWords,
                entry: hasAnsi ? _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ansicolor"].strip(message) : message,
                raw: message,
                labels: series.labels,
                timestamp: ts,
            });
        }
    }
    // Meta data to display in status
    var meta = [];
    if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.size(commonLabels) > 0) {
        meta.push({
            label: 'Common labels',
            value: commonLabels,
            kind: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsMetaKind"].LabelsMap,
        });
    }
    var limits = logSeries.filter(function (series) { return series.meta && series.meta.limit; });
    if (limits.length > 0) {
        meta.push({
            label: 'Limit',
            value: limits[0].meta.limit + " (" + rows.length + " returned)",
            kind: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsMetaKind"].String,
        });
    }
    return {
        hasUniqueLabels: hasUniqueLabels,
        meta: meta,
        rows: rows,
    };
}


/***/ }),

/***/ "./public/app/core/middlewares/application.ts":
/*!****************************************************!*\
  !*** ./public/app/core/middlewares/application.ts ***!
  \****************************************************/
/*! exports provided: toggleLogActionsMiddleware */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggleLogActionsMiddleware", function() { return toggleLogActionsMiddleware; });
/* harmony import */ var _actions_application__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../actions/application */ "./public/app/core/actions/application.ts");

var toggleLogActionsMiddleware = function (store) { return function (next) { return function (action) {
    var isLogActionsAction = action.type === _actions_application__WEBPACK_IMPORTED_MODULE_0__["toggleLogActions"].type;
    if (isLogActionsAction) {
        return next(action);
    }
    var logActionsTrue = window && window.location && window.location.search && window.location.search.indexOf('logActions=true') !== -1;
    var logActionsFalse = window && window.location && window.location.search && window.location.search.indexOf('logActions=false') !== -1;
    var logActions = store.getState().application.logActions;
    if (logActionsTrue && !logActions) {
        store.dispatch(Object(_actions_application__WEBPACK_IMPORTED_MODULE_0__["toggleLogActions"])());
    }
    if (logActionsFalse && logActions) {
        store.dispatch(Object(_actions_application__WEBPACK_IMPORTED_MODULE_0__["toggleLogActions"])());
    }
    return next(action);
}; }; };


/***/ }),

/***/ "./public/app/core/nav_model_srv.ts":
/*!******************************************!*\
  !*** ./public/app/core/nav_model_srv.ts ***!
  \******************************************/
/*! exports provided: NavModelSrv, getNotFoundNav, getWarningNav */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavModelSrv", function() { return NavModelSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNotFoundNav", function() { return getNotFoundNav; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getWarningNav", function() { return getWarningNav; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);




var NavModelSrv = /** @class */ (function () {
    /** @ngInject */
    function NavModelSrv() {
        this.navItems = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].bootData.navTree;
    }
    NavModelSrv.prototype.getCfgNode = function () {
        return lodash__WEBPACK_IMPORTED_MODULE_3___default.a.find(this.navItems, { id: 'cfg' });
    };
    NavModelSrv.prototype.getNav = function () {
        var e_1, _a, e_2, _b;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var children = this.navItems;
        var nav = {
            breadcrumbs: [],
        };
        try {
            for (var args_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](args), args_1_1 = args_1.next(); !args_1_1.done; args_1_1 = args_1.next()) {
                var id = args_1_1.value;
                // if its a number then it's the index to use for main
                if (lodash__WEBPACK_IMPORTED_MODULE_3___default.a.isNumber(id)) {
                    nav.main = nav.breadcrumbs[id];
                    break;
                }
                var node = lodash__WEBPACK_IMPORTED_MODULE_3___default.a.find(children, { id: id });
                nav.breadcrumbs.push(node);
                nav.node = node;
                nav.main = node;
                children = node.children;
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (args_1_1 && !args_1_1.done && (_a = args_1.return)) _a.call(args_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        if (nav.main.children) {
            try {
                for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](nav.main.children), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var item = _d.value;
                    item.active = false;
                    if (item.url === nav.node.url) {
                        item.active = true;
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }
        return nav;
    };
    NavModelSrv.prototype.getNotFoundNav = function () {
        return getNotFoundNav(); // the exported function
    };
    return NavModelSrv;
}());

function getNotFoundNav() {
    return getWarningNav('Page not found', '404 Error');
}
function getWarningNav(text, subTitle) {
    var node = {
        text: text,
        subTitle: subTitle,
        icon: 'fa fa-fw fa-warning',
    };
    return {
        breadcrumbs: [node],
        node: node,
        main: node,
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('navModelSrv', NavModelSrv);


/***/ }),

/***/ "./public/app/core/partials.ts":
/*!*************************************!*\
  !*** ./public/app/core/partials.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var templates = __webpack_require__("./public/app sync recursive \\.html$");
templates.keys().forEach(function (key) {
    templates(key);
});


/***/ }),

/***/ "./public/app/core/profiler.ts":
/*!*************************************!*\
  !*** ./public/app/core/profiler.ts ***!
  \*************************************/
/*! exports provided: Profiler, profiler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Profiler", function() { return Profiler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "profiler", function() { return profiler; });
var Profiler = /** @class */ (function () {
    function Profiler() {
    }
    Profiler.prototype.init = function (config, $rootScope) {
        this.$rootScope = $rootScope;
        this.window = window;
        if (!this.enabled) {
            return;
        }
    };
    Profiler.prototype.renderingCompleted = function () {
        // add render counter to root scope
        // used by phantomjs render.js to know when panel has rendered
        this.panelsRendered = (this.panelsRendered || 0) + 1;
        // this window variable is used by backend rendering tools to know
        // all panels have completed rendering
        this.window.panelsRendered = this.panelsRendered;
    };
    return Profiler;
}());

var profiler = new Profiler();



/***/ }),

/***/ "./public/app/core/reducers/appNotification.ts":
/*!*****************************************************!*\
  !*** ./public/app/core/reducers/appNotification.ts ***!
  \*****************************************************/
/*! exports provided: initialState, appNotificationsReducer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appNotificationsReducer", function() { return appNotificationsReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions_appNotification__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../actions/appNotification */ "./public/app/core/actions/appNotification.ts");


var initialState = {
    appNotifications: [],
};
var appNotificationsReducer = function (state, action) {
    if (state === void 0) { state = initialState; }
    switch (action.type) {
        case _actions_appNotification__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].AddAppNotification:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { appNotifications: state.appNotifications.concat([action.payload]) });
        case _actions_appNotification__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].ClearAppNotification:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { appNotifications: state.appNotifications.filter(function (appNotification) { return appNotification.id !== action.payload; }) });
    }
    return state;
};


/***/ }),

/***/ "./public/app/core/reducers/application.ts":
/*!*************************************************!*\
  !*** ./public/app/core/reducers/application.ts ***!
  \*************************************************/
/*! exports provided: initialState, applicationReducer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applicationReducer", function() { return applicationReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var _actions_application__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../actions/application */ "./public/app/core/actions/application.ts");



var initialState = {
    logActions: false,
};
var applicationReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["reducerFactory"])(initialState)
    .addMapper({
    filter: _actions_application__WEBPACK_IMPORTED_MODULE_2__["toggleLogActions"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { logActions: !state.logActions })); },
})
    .create();


/***/ }),

/***/ "./public/app/core/reducers/index.ts":
/*!*******************************************!*\
  !*** ./public/app/core/reducers/index.ts ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./navModel */ "./public/app/core/reducers/navModel.ts");
/* harmony import */ var _location__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./location */ "./public/app/core/reducers/location.ts");
/* harmony import */ var _appNotification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./appNotification */ "./public/app/core/reducers/appNotification.ts");
/* harmony import */ var _application__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./application */ "./public/app/core/reducers/application.ts");




/* harmony default export */ __webpack_exports__["default"] = ({
    navIndex: _navModel__WEBPACK_IMPORTED_MODULE_0__["navIndexReducer"],
    location: _location__WEBPACK_IMPORTED_MODULE_1__["locationReducer"],
    appNotifications: _appNotification__WEBPACK_IMPORTED_MODULE_2__["appNotificationsReducer"],
    application: _application__WEBPACK_IMPORTED_MODULE_3__["applicationReducer"],
});


/***/ }),

/***/ "./public/app/core/reducers/location.ts":
/*!**********************************************!*\
  !*** ./public/app/core/reducers/location.ts ***!
  \**********************************************/
/*! exports provided: initialState, locationReducer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "locationReducer", function() { return locationReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_utils_url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/url */ "./public/app/core/utils/url.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");





var initialState = {
    url: '',
    path: '',
    query: {},
    routeParams: {},
    replace: false,
    lastUpdated: 0,
};
var locationReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_3__["reducerFactory"])(initialState)
    .addMapper({
    filter: app_core_actions__WEBPACK_IMPORTED_MODULE_4__["updateLocation"],
    mapper: function (state, action) {
        var _a = action.payload, path = _a.path, routeParams = _a.routeParams, replace = _a.replace;
        var query = action.payload.query || state.query;
        if (action.payload.partial) {
            query = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.defaults(query, state.query);
            query = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.omitBy(query, lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNull);
        }
        return {
            url: Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_1__["renderUrl"])(path || state.path, query),
            path: path || state.path,
            query: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query),
            routeParams: routeParams || state.routeParams,
            replace: replace === true,
            lastUpdated: new Date().getTime(),
        };
    },
})
    .create();


/***/ }),

/***/ "./public/app/core/reducers/navModel.ts":
/*!**********************************************!*\
  !*** ./public/app/core/reducers/navModel.ts ***!
  \**********************************************/
/*! exports provided: buildInitialState, initialState, navIndexReducer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildInitialState", function() { return buildInitialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "navIndexReducer", function() { return navIndexReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_actions_navModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/actions/navModel */ "./public/app/core/actions/navModel.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



function buildInitialState() {
    var navIndex = {};
    var rootNodes = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].bootData.navTree;
    buildNavIndex(navIndex, rootNodes);
    return navIndex;
}
function buildNavIndex(navIndex, children, parentItem) {
    var e_1, _a;
    try {
        for (var children_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](children), children_1_1 = children_1.next(); !children_1_1.done; children_1_1 = children_1.next()) {
            var node = children_1_1.value;
            navIndex[node.id] = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, node, { parentItem: parentItem });
            if (node.children) {
                buildNavIndex(navIndex, node.children, node);
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (children_1_1 && !children_1_1.done && (_a = children_1.return)) _a.call(children_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
}
var initialState = buildInitialState();
var navIndexReducer = function (state, action) {
    var e_2, _a;
    if (state === void 0) { state = initialState; }
    switch (action.type) {
        case app_core_actions_navModel__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].UpdateNavIndex:
            var newPages = {};
            var payload = action.payload;
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](payload.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var node = _c.value;
                    newPages[node.id] = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, node, { parentItem: payload });
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, newPages);
    }
    return state;
};


/***/ }),

/***/ "./public/app/core/redux/actionCreatorFactory.ts":
/*!*******************************************************!*\
  !*** ./public/app/core/redux/actionCreatorFactory.ts ***!
  \*******************************************************/
/*! exports provided: actionCreatorFactory, noPayloadActionCreatorFactory, getNoPayloadActionCreatorMock, mockActionCreator, resetAllActionCreatorTypes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "actionCreatorFactory", function() { return actionCreatorFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "noPayloadActionCreatorFactory", function() { return noPayloadActionCreatorFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNoPayloadActionCreatorMock", function() { return getNoPayloadActionCreatorMock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mockActionCreator", function() { return mockActionCreator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetAllActionCreatorTypes", function() { return resetAllActionCreatorTypes; });
var allActionCreators = [];
var actionCreatorFactory = function (type) {
    var create = function () {
        return Object.assign(function (payload) { return ({ type: type, payload: payload }); }, { type: type });
    };
    if (allActionCreators.some(function (t) { return (t && type ? t.toLocaleUpperCase() === type.toLocaleUpperCase() : false); })) {
        throw new Error("There is already an actionCreator defined with the type " + type);
    }
    allActionCreators.push(type);
    return { create: create };
};
var noPayloadActionCreatorFactory = function (type) {
    var create = function () {
        return Object.assign(function () { return ({ type: type, payload: undefined }); }, { type: type });
    };
    if (allActionCreators.some(function (t) { return (t && type ? t.toLocaleUpperCase() === type.toLocaleUpperCase() : false); })) {
        throw new Error("There is already an actionCreator defined with the type " + type);
    }
    allActionCreators.push(type);
    return { create: create };
};
var getNoPayloadActionCreatorMock = function (creator) {
    var mock = Object.assign(function () {
        mock.calls++;
        return { type: creator.type, payload: undefined };
    }, { type: creator.type, calls: 0 });
    return mock;
};
var mockActionCreator = function (creator) {
    return Object.assign(jest.fn(), creator);
};
// Should only be used by tests
var resetAllActionCreatorTypes = function () { return (allActionCreators.length = 0); };


/***/ }),

/***/ "./public/app/core/redux/index.ts":
/*!****************************************!*\
  !*** ./public/app/core/redux/index.ts ***!
  \****************************************/
/*! exports provided: actionCreatorFactory, noPayloadActionCreatorFactory, getNoPayloadActionCreatorMock, mockActionCreator, resetAllActionCreatorTypes, reducerFactory */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./actionCreatorFactory */ "./public/app/core/redux/actionCreatorFactory.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "actionCreatorFactory", function() { return _actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "noPayloadActionCreatorFactory", function() { return _actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["noPayloadActionCreatorFactory"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "getNoPayloadActionCreatorMock", function() { return _actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["getNoPayloadActionCreatorMock"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mockActionCreator", function() { return _actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["mockActionCreator"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "resetAllActionCreatorTypes", function() { return _actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["resetAllActionCreatorTypes"]; });

/* harmony import */ var _reducerFactory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reducerFactory */ "./public/app/core/redux/reducerFactory.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reducerFactory", function() { return _reducerFactory__WEBPACK_IMPORTED_MODULE_1__["reducerFactory"]; });





/***/ }),

/***/ "./public/app/core/redux/reducerFactory.ts":
/*!*************************************************!*\
  !*** ./public/app/core/redux/reducerFactory.ts ***!
  \*************************************************/
/*! exports provided: reducerFactory */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reducerFactory", function() { return reducerFactory; });
var reducerFactory = function (initialState) {
    var allMappers = {};
    var addMapper = function (config) {
        if (allMappers[config.filter.type]) {
            throw new Error("There is already a mapper defined with the type " + config.filter.type);
        }
        allMappers[config.filter.type] = config.mapper;
        return instance;
    };
    var create = function () { return function (state, action) {
        if (state === void 0) { state = initialState; }
        var mapper = allMappers[action.type];
        if (mapper) {
            return mapper(state, action);
        }
        return state;
    }; };
    var instance = { addMapper: addMapper, create: create };
    return instance;
};


/***/ }),

/***/ "./public/app/core/selectors/navModel.ts":
/*!***********************************************!*\
  !*** ./public/app/core/selectors/navModel.ts ***!
  \***********************************************/
/*! exports provided: getNavModel, getTitleFromNavModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNavModel", function() { return getNavModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTitleFromNavModel", function() { return getTitleFromNavModel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

function getNotFoundModel() {
    var node = {
        id: 'not-found',
        text: 'Page not found',
        icon: 'fa fa-fw fa-warning',
        subTitle: '404 Error',
        url: 'not-found',
    };
    return {
        node: node,
        main: node,
    };
}
function getNavModel(navIndex, id, fallback) {
    if (navIndex[id]) {
        var node_1 = navIndex[id];
        var main = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, node_1.parentItem);
        main.children = main.children.map(function (item) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, item, { active: item.url === node_1.url });
        });
        return {
            node: node_1,
            main: main,
        };
    }
    if (fallback) {
        return fallback;
    }
    return getNotFoundModel();
}
var getTitleFromNavModel = function (navModel) {
    return "" + navModel.main.text + (navModel.node.text ? ': ' + navModel.node.text : '');
};


/***/ }),

/***/ "./public/app/core/services/AngularLoader.ts":
/*!***************************************************!*\
  !*** ./public/app/core/services/AngularLoader.ts ***!
  \***************************************************/
/*! exports provided: AngularLoader, setAngularLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AngularLoader", function() { return AngularLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setAngularLoader", function() { return setAngularLoader; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");




var AngularLoader = /** @class */ (function () {
    /** @ngInject */
    function AngularLoader($compile, $rootScope) {
        this.$compile = $compile;
        this.$rootScope = $rootScope;
    }
    AngularLoader.prototype.load = function (elem, scopeProps, template) {
        var scope = this.$rootScope.$new();
        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.assign(scope, scopeProps);
        var compiledElem = this.$compile(template)(scope);
        var rootNode = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(elem);
        rootNode.append(compiledElem);
        return {
            destroy: function () {
                scope.$destroy();
                compiledElem.remove();
            },
            digest: function () {
                if (!scope.$$phase) {
                    scope.$digest();
                }
            },
            getScope: function () {
                return scope;
            },
        };
    };
    return AngularLoader;
}());

function setAngularLoader(v) {
    Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_3__["setAngularLoader"])(v);
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('angularLoader', AngularLoader);


/***/ }),

/***/ "./public/app/core/services/alert_srv.ts":
/*!***********************************************!*\
  !*** ./public/app/core/services/alert_srv.ts ***!
  \***********************************************/
/*! exports provided: AlertSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertSrv", function() { return AlertSrv; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var AlertSrv = /** @class */ (function () {
    function AlertSrv() {
    }
    AlertSrv.prototype.set = function () {
        console.log('old depricated alert srv being used');
    };
    return AlertSrv;
}());

// this is just added to not break old plugins that might be using it
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].service('alertSrv', AlertSrv);


/***/ }),

/***/ "./public/app/core/services/all.ts":
/*!*****************************************!*\
  !*** ./public/app/core/services/all.ts ***!
  \*****************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _alert_srv__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./alert_srv */ "./public/app/core/services/alert_srv.ts");
/* harmony import */ var _util_srv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util_srv */ "./public/app/core/services/util_srv.ts");
/* harmony import */ var _context_srv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./context_srv */ "./public/app/core/services/context_srv.ts");
/* harmony import */ var _timer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timer */ "./public/app/core/services/timer.ts");
/* harmony import */ var _analytics__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./analytics */ "./public/app/core/services/analytics.ts");
/* harmony import */ var _popover_srv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./popover_srv */ "./public/app/core/services/popover_srv.ts");
/* harmony import */ var _segment_srv__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./segment_srv */ "./public/app/core/services/segment_srv.ts");
/* harmony import */ var _backend_srv__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./backend_srv */ "./public/app/core/services/backend_srv.ts");
/* harmony import */ var _dynamic_directive_srv__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./dynamic_directive_srv */ "./public/app/core/services/dynamic_directive_srv.ts");
/* harmony import */ var _bridge_srv__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./bridge_srv */ "./public/app/core/services/bridge_srv.ts");












/***/ }),

/***/ "./public/app/core/services/analytics.ts":
/*!***********************************************!*\
  !*** ./public/app/core/services/analytics.ts ***!
  \***********************************************/
/*! exports provided: Analytics */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Analytics", function() { return Analytics; });
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



var Analytics = /** @class */ (function () {
    /** @ngInject */
    function Analytics($rootScope, $location) {
        this.$rootScope = $rootScope;
        this.$location = $location;
    }
    Analytics.prototype.gaInit = function () {
        jquery__WEBPACK_IMPORTED_MODULE_0___default.a.ajax({
            url: 'https://www.google-analytics.com/analytics.js',
            dataType: 'script',
            cache: true,
        });
        var ga = (window.ga =
            window.ga ||
                //tslint:disable-next-line:only-arrow-functions
                function () {
                    (ga.q = ga.q || []).push(arguments);
                });
        ga.l = +new Date();
        ga('create', app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].googleAnalyticsId, 'auto');
        ga('set', 'anonymizeIp', true);
        return ga;
    };
    Analytics.prototype.init = function () {
        var _this = this;
        this.$rootScope.$on('$viewContentLoaded', function () {
            var track = { page: _this.$location.url() };
            var ga = window.ga || _this.gaInit();
            ga('set', track);
            ga('send', 'pageview');
        });
    };
    return Analytics;
}());

/** @ngInject */
function startAnalytics(googleAnalyticsSrv) {
    if (app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].googleAnalyticsId) {
        googleAnalyticsSrv.init();
    }
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('googleAnalyticsSrv', Analytics).run(startAnalytics);


/***/ }),

/***/ "./public/app/core/services/backend_srv.ts":
/*!*************************************************!*\
  !*** ./public/app/core/services/backend_srv.ts ***!
  \*************************************************/
/*! exports provided: BackendSrv, getBackendSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackendSrv", function() { return BackendSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBackendSrv", function() { return getBackendSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_features_dashboard_state_DashboardModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/dashboard/state/DashboardModel */ "./public/app/features/dashboard/state/DashboardModel.ts");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");







var BackendSrv = /** @class */ (function () {
    /** @ngInject */
    function BackendSrv($http, $q, $timeout, contextSrv) {
        this.$http = $http;
        this.$q = $q;
        this.$timeout = $timeout;
        this.contextSrv = contextSrv;
        this.inFlightRequests = {};
        this.HTTP_REQUEST_CANCELED = -1;
    }
    BackendSrv.prototype.get = function (url, params) {
        return this.request({ method: 'GET', url: url, params: params });
    };
    BackendSrv.prototype.delete = function (url) {
        return this.request({ method: 'DELETE', url: url });
    };
    BackendSrv.prototype.post = function (url, data) {
        return this.request({ method: 'POST', url: url, data: data });
    };
    BackendSrv.prototype.patch = function (url, data) {
        return this.request({ method: 'PATCH', url: url, data: data });
    };
    BackendSrv.prototype.put = function (url, data) {
        return this.request({ method: 'PUT', url: url, data: data });
    };
    BackendSrv.prototype.withNoBackendCache = function (callback) {
        var _this = this;
        this.noBackendCache = true;
        return callback().finally(function () {
            _this.noBackendCache = false;
        });
    };
    BackendSrv.prototype.requestErrorHandler = function (err) {
        if (err.isHandled) {
            return;
        }
        var data = err.data || { message: 'Unexpected error' };
        if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isString(data)) {
            data = { message: data };
        }
        if (err.status === 422) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('alert-warning', ['Validation failed', data.message]);
            throw data;
        }
        var severity = 'error';
        if (err.status < 500) {
            severity = 'warning';
        }
        if (data.message) {
            var description = '';
            var message = data.message;
            if (message.length > 80) {
                description = message;
                message = 'Error';
            }
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('alert-' + severity, [message, description]);
        }
        throw data;
    };
    BackendSrv.prototype.request = function (options) {
        var _this = this;
        options.retry = options.retry || 0;
        var requestIsLocal = !options.url.match(/^http/);
        var firstAttempt = options.retry === 0;
        if (requestIsLocal) {
            if (this.contextSrv.user && this.contextSrv.user.orgId) {
                options.headers = options.headers || {};
                options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
            }
            if (options.url.indexOf('/') === 0) {
                options.url = options.url.substring(1);
            }
        }
        return this.$http(options).then(function (results) {
            if (options.method !== 'GET') {
                if (results && results.data.message) {
                    if (options.showSuccessAlert !== false) {
                        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('alert-success', [results.data.message]);
                    }
                }
            }
            return results.data;
        }, function (err) {
            // handle unauthorized
            if (err.status === 401 && _this.contextSrv.user.isSignedIn && firstAttempt) {
                return _this.loginPing()
                    .then(function () {
                    options.retry = 1;
                    return _this.request(options);
                })
                    .catch(function (err) {
                    if (err.status === 401) {
                        window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].appSubUrl + '/logout';
                        throw err;
                    }
                });
            }
            _this.$timeout(_this.requestErrorHandler.bind(_this, err), 50);
            throw err;
        });
    };
    BackendSrv.prototype.addCanceler = function (requestId, canceler) {
        if (requestId in this.inFlightRequests) {
            this.inFlightRequests[requestId].push(canceler);
        }
        else {
            this.inFlightRequests[requestId] = [canceler];
        }
    };
    BackendSrv.prototype.resolveCancelerIfExists = function (requestId) {
        var cancelers = this.inFlightRequests[requestId];
        if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isUndefined(cancelers) && cancelers.length) {
            cancelers[0].resolve();
        }
    };
    BackendSrv.prototype.datasourceRequest = function (options) {
        var _this = this;
        var canceler = null;
        options.retry = options.retry || 0;
        // A requestID is provided by the datasource as a unique identifier for a
        // particular query. If the requestID exists, the promise it is keyed to
        // is canceled, canceling the previous datasource request if it is still
        // in-flight.
        var requestId = options.requestId;
        if (requestId) {
            this.resolveCancelerIfExists(requestId);
            // create new canceler
            canceler = this.$q.defer();
            options.timeout = canceler.promise;
            this.addCanceler(requestId, canceler);
        }
        var requestIsLocal = !options.url.match(/^http/);
        var firstAttempt = options.retry === 0;
        if (requestIsLocal) {
            if (this.contextSrv.user && this.contextSrv.user.orgId) {
                options.headers = options.headers || {};
                options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
            }
            if (options.url.indexOf('/') === 0) {
                options.url = options.url.substring(1);
            }
            if (options.headers && options.headers.Authorization) {
                options.headers['X-DS-Authorization'] = options.headers.Authorization;
                delete options.headers.Authorization;
            }
            if (this.noBackendCache) {
                options.headers['X-Grafana-NoCache'] = 'true';
            }
        }
        return this.$http(options)
            .then(function (response) {
            if (!options.silent) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('ds-request-response', response);
            }
            return response;
        })
            .catch(function (err) {
            if (err.status === _this.HTTP_REQUEST_CANCELED) {
                throw { err: err, cancelled: true };
            }
            // handle unauthorized for backend requests
            if (requestIsLocal && firstAttempt && err.status === 401) {
                return _this.loginPing()
                    .then(function () {
                    options.retry = 1;
                    if (canceler) {
                        canceler.resolve();
                    }
                    return _this.datasourceRequest(options);
                })
                    .catch(function (err) {
                    if (err.status === 401) {
                        window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].appSubUrl + '/logout';
                        throw err;
                    }
                });
            }
            // populate error obj on Internal Error
            if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isString(err.data) && err.status === 500) {
                err.data = {
                    error: err.statusText,
                    response: err.data,
                };
            }
            // for Prometheus
            if (err.data && !err.data.message && lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isString(err.data.error)) {
                err.data.message = err.data.error;
            }
            if (!options.silent) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('ds-request-error', err);
            }
            throw err;
        })
            .finally(function () {
            // clean up
            if (options.requestId) {
                _this.inFlightRequests[options.requestId].shift();
            }
        });
    };
    BackendSrv.prototype.loginPing = function () {
        return this.request({ url: '/api/login/ping', method: 'GET', retry: 1 });
    };
    BackendSrv.prototype.search = function (query) {
        return this.get('/api/search', query);
    };
    BackendSrv.prototype.getDashboardBySlug = function (slug) {
        return this.get("/api/dashboards/db/" + slug);
    };
    BackendSrv.prototype.getDashboardByUid = function (uid) {
        return this.get("/api/dashboards/uid/" + uid);
    };
    BackendSrv.prototype.getFolderByUid = function (uid) {
        return this.get("/api/folders/" + uid);
    };
    BackendSrv.prototype.saveDashboard = function (dash, _a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.message, message = _c === void 0 ? '' : _c, folderId = _b.folderId, _d = _b.overwrite, overwrite = _d === void 0 ? false : _d;
        return this.post('/api/dashboards/db/', {
            dashboard: dash,
            folderId: folderId,
            overwrite: overwrite,
            message: message,
        });
    };
    BackendSrv.prototype.createFolder = function (payload) {
        return this.post('/api/folders', payload);
    };
    BackendSrv.prototype.deleteFolder = function (uid, showSuccessAlert) {
        return this.request({ method: 'DELETE', url: "/api/folders/" + uid, showSuccessAlert: showSuccessAlert === true });
    };
    BackendSrv.prototype.deleteDashboard = function (uid, showSuccessAlert) {
        return this.request({
            method: 'DELETE',
            url: "/api/dashboards/uid/" + uid,
            showSuccessAlert: showSuccessAlert === true,
        });
    };
    BackendSrv.prototype.deleteFoldersAndDashboards = function (folderUids, dashboardUids) {
        var e_1, _a, e_2, _b;
        var tasks = [];
        try {
            for (var folderUids_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](folderUids), folderUids_1_1 = folderUids_1.next(); !folderUids_1_1.done; folderUids_1_1 = folderUids_1.next()) {
                var folderUid = folderUids_1_1.value;
                tasks.push(this.createTask(this.deleteFolder.bind(this), true, folderUid, true));
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (folderUids_1_1 && !folderUids_1_1.done && (_a = folderUids_1.return)) _a.call(folderUids_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        try {
            for (var dashboardUids_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboardUids), dashboardUids_1_1 = dashboardUids_1.next(); !dashboardUids_1_1.done; dashboardUids_1_1 = dashboardUids_1.next()) {
                var dashboardUid = dashboardUids_1_1.value;
                tasks.push(this.createTask(this.deleteDashboard.bind(this), true, dashboardUid, true));
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (dashboardUids_1_1 && !dashboardUids_1_1.done && (_b = dashboardUids_1.return)) _b.call(dashboardUids_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return this.executeInOrder(tasks, []);
    };
    BackendSrv.prototype.moveDashboards = function (dashboardUids, toFolder) {
        var e_3, _a;
        var tasks = [];
        try {
            for (var dashboardUids_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboardUids), dashboardUids_2_1 = dashboardUids_2.next(); !dashboardUids_2_1.done; dashboardUids_2_1 = dashboardUids_2.next()) {
                var uid = dashboardUids_2_1.value;
                tasks.push(this.createTask(this.moveDashboard.bind(this), true, uid, toFolder));
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (dashboardUids_2_1 && !dashboardUids_2_1.done && (_a = dashboardUids_2.return)) _a.call(dashboardUids_2);
            }
            finally { if (e_3) throw e_3.error; }
        }
        return this.executeInOrder(tasks, []).then(function (result) {
            return {
                totalCount: result.length,
                successCount: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(result, { succeeded: true }).length,
                alreadyInFolderCount: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(result, { alreadyInFolder: true }).length,
            };
        });
    };
    BackendSrv.prototype.moveDashboard = function (uid, toFolder) {
        var _this = this;
        var deferred = this.$q.defer();
        this.getDashboardByUid(uid).then(function (fullDash) {
            var model = new app_features_dashboard_state_DashboardModel__WEBPACK_IMPORTED_MODULE_5__["DashboardModel"](fullDash.dashboard, fullDash.meta);
            if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
                deferred.resolve({ alreadyInFolder: true });
                return;
            }
            var clone = model.getSaveModelClone();
            var options = {
                folderId: toFolder.id,
                overwrite: false,
            };
            _this.saveDashboard(clone, options)
                .then(function () {
                deferred.resolve({ succeeded: true });
            })
                .catch(function (err) {
                if (err.data && err.data.status === 'plugin-dashboard') {
                    err.isHandled = true;
                    options.overwrite = true;
                    _this.saveDashboard(clone, options)
                        .then(function () {
                        deferred.resolve({ succeeded: true });
                    })
                        .catch(function (err) {
                        deferred.resolve({ succeeded: false });
                    });
                }
                else {
                    deferred.resolve({ succeeded: false });
                }
            });
        });
        return deferred.promise;
    };
    BackendSrv.prototype.createTask = function (fn, ignoreRejections) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        return function (result) {
            return fn
                .apply(null, args)
                .then(function (res) {
                return Array.prototype.concat(result, [res]);
            })
                .catch(function (err) {
                if (ignoreRejections) {
                    return result;
                }
                throw err;
            });
        };
    };
    BackendSrv.prototype.executeInOrder = function (tasks, initialValue) {
        return tasks.reduce(this.$q.when, initialValue);
    };
    return BackendSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].service('backendSrv', BackendSrv);
// Used for testing and things that really need BackendSrv
function getBackendSrv() {
    return Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_6__["getBackendSrv"])();
}


/***/ }),

/***/ "./public/app/core/services/bridge_srv.ts":
/*!************************************************!*\
  !*** ./public/app/core/services/bridge_srv.ts ***!
  \************************************************/
/*! exports provided: BridgeSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BridgeSrv", function() { return BridgeSrv; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_store_store__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/store/store */ "./public/app/store/store.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");





// Services that handles angular -> redux store sync & other react <-> angular sync
var BridgeSrv = /** @class */ (function () {
    /** @ngInject */
    function BridgeSrv($location, $timeout, $window, $rootScope, $route) {
        this.$location = $location;
        this.$timeout = $timeout;
        this.$window = $window;
        this.$rootScope = $rootScope;
        this.$route = $route;
        this.fullPageReloadRoutes = ['/logout'];
    }
    BridgeSrv.prototype.init = function () {
        var _this = this;
        this.$rootScope.$on('$routeUpdate', function (evt, data) {
            var angularUrl = _this.$location.url();
            var state = app_store_store__WEBPACK_IMPORTED_MODULE_2__["store"].getState();
            if (state.location.url !== angularUrl) {
                app_store_store__WEBPACK_IMPORTED_MODULE_2__["store"].dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_4__["updateLocation"])({
                    path: _this.$location.path(),
                    query: _this.$location.search(),
                    routeParams: _this.$route.current.params,
                }));
            }
        });
        this.$rootScope.$on('$routeChangeSuccess', function (evt, data) {
            app_store_store__WEBPACK_IMPORTED_MODULE_2__["store"].dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_4__["updateLocation"])({
                path: _this.$location.path(),
                query: _this.$location.search(),
                routeParams: _this.$route.current.params,
            }));
        });
        // Listen for changes in redux location -> update angular location
        app_store_store__WEBPACK_IMPORTED_MODULE_2__["store"].subscribe(function () {
            var state = app_store_store__WEBPACK_IMPORTED_MODULE_2__["store"].getState();
            var angularUrl = _this.$location.url();
            var url = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__["default"].stripBaseFromUrl(state.location.url);
            if (angularUrl !== url) {
                _this.$timeout(function () {
                    _this.$location.url(url);
                    // some state changes should not trigger new browser history
                    if (state.location.replace) {
                        _this.$location.replace();
                    }
                });
                console.log('store updating angular $location.url', url);
            }
        });
        app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].on('location-change', function (payload) {
            var urlWithoutBase = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__["default"].stripBaseFromUrl(payload.href);
            if (_this.fullPageReloadRoutes.indexOf(urlWithoutBase) > -1) {
                _this.$window.location.href = payload.href;
                return;
            }
            _this.$timeout(function () {
                // A hack to use timeout when we're changing things (in this case the url) from outside of Angular.
                _this.$location.url(urlWithoutBase);
            });
        });
    };
    return BridgeSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].service('bridgeSrv', BridgeSrv);


/***/ }),

/***/ "./public/app/core/services/context_srv.ts":
/*!*************************************************!*\
  !*** ./public/app/core/services/context_srv.ts ***!
  \*************************************************/
/*! exports provided: User, ContextSrv, contextSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "User", function() { return User; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContextSrv", function() { return ContextSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contextSrv", function() { return contextSrv; });
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");



var User = /** @class */ (function () {
    function User() {
        if (app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData.user) {
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.extend(this, app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData.user);
        }
    }
    return User;
}());

var ContextSrv = /** @class */ (function () {
    function ContextSrv() {
        this.sidemenuSmallBreakpoint = false;
        if (!app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData) {
            app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData = { user: {}, settings: {} };
        }
        this.user = new User();
        this.isSignedIn = this.user.isSignedIn;
        this.isGrafanaAdmin = this.user.isGrafanaAdmin;
        this.isEditor = this.hasRole('Editor') || this.hasRole('Admin');
        this.hasEditPermissionInFolders = this.user.hasEditPermissionInFolders;
    }
    ContextSrv.prototype.hasRole = function (role) {
        return this.user.orgRole === role;
    };
    ContextSrv.prototype.isGrafanaVisible = function () {
        return !!(document.visibilityState === undefined || document.visibilityState === 'visible');
    };
    ContextSrv.prototype.hasAccessToExplore = function () {
        return (this.isEditor || app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].viewersCanEdit) && app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].exploreEnabled;
    };
    return ContextSrv;
}());

var contextSrv = new ContextSrv();

app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].factory('contextSrv', function () {
    return contextSrv;
});


/***/ }),

/***/ "./public/app/core/services/dynamic_directive_srv.ts":
/*!***********************************************************!*\
  !*** ./public/app/core/services/dynamic_directive_srv.ts ***!
  \***********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


var DynamicDirectiveSrv = /** @class */ (function () {
    /** @ngInject */
    function DynamicDirectiveSrv($compile) {
        this.$compile = $compile;
    }
    DynamicDirectiveSrv.prototype.addDirective = function (element, name, scope) {
        var child = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(document.createElement(name));
        this.$compile(child)(scope);
        element.empty();
        element.append(child);
    };
    DynamicDirectiveSrv.prototype.link = function (scope, elem, attrs, options) {
        var directiveInfo = options.directive(scope);
        if (!directiveInfo || !directiveInfo.fn) {
            elem.empty();
            return;
        }
        if (!directiveInfo.fn.registered) {
            _core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive(attrs.$normalize(directiveInfo.name), directiveInfo.fn);
            directiveInfo.fn.registered = true;
        }
        this.addDirective(elem, directiveInfo.name, scope);
    };
    DynamicDirectiveSrv.prototype.create = function (options) {
        var _this = this;
        var directiveDef = {
            restrict: 'E',
            scope: options.scope,
            link: function (scope, elem, attrs) {
                if (options.watchPath) {
                    var childScope_1 = null;
                    scope.$watch(options.watchPath, function () {
                        if (childScope_1) {
                            childScope_1.$destroy();
                        }
                        childScope_1 = scope.$new();
                        _this.link(childScope_1, elem, attrs, options);
                    });
                }
                else {
                    _this.link(scope, elem, attrs, options);
                }
            },
        };
        return directiveDef;
    };
    return DynamicDirectiveSrv;
}());
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('dynamicDirectiveSrv', DynamicDirectiveSrv);


/***/ }),

/***/ "./public/app/core/services/impression_srv.ts":
/*!****************************************************!*\
  !*** ./public/app/core/services/impression_srv.ts ***!
  \****************************************************/
/*! exports provided: ImpressionSrv, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImpressionSrv", function() { return ImpressionSrv; });
/* harmony import */ var app_core_store__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/store */ "./public/app/core/store.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



var ImpressionSrv = /** @class */ (function () {
    function ImpressionSrv() {
    }
    ImpressionSrv.prototype.addDashboardImpression = function (dashboardId) {
        var impressionsKey = this.impressionKey();
        var impressions = [];
        if (app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].exists(impressionsKey)) {
            impressions = JSON.parse(app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].get(impressionsKey));
            if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(impressions)) {
                impressions = [];
            }
        }
        impressions = impressions.filter(function (imp) {
            return dashboardId !== imp;
        });
        impressions.unshift(dashboardId);
        if (impressions.length > 50) {
            impressions.pop();
        }
        app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].set(impressionsKey, JSON.stringify(impressions));
    };
    ImpressionSrv.prototype.getDashboardOpened = function () {
        var impressions = app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].get(this.impressionKey()) || '[]';
        impressions = JSON.parse(impressions);
        impressions = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(impressions, function (el) {
            return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(el);
        });
        return impressions;
    };
    ImpressionSrv.prototype.impressionKey = function () {
        return 'dashboard_impressions-' + app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].bootData.user.orgId;
    };
    return ImpressionSrv;
}());

var impressionSrv = new ImpressionSrv();
/* harmony default export */ __webpack_exports__["default"] = (impressionSrv);


/***/ }),

/***/ "./public/app/core/services/keybindingSrv.ts":
/*!***************************************************!*\
  !*** ./public/app/core/services/keybindingSrv.ts ***!
  \***************************************************/
/*! exports provided: KeybindingSrv, setKeybindingSrv, getKeybindingSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeybindingSrv", function() { return KeybindingSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setKeybindingSrv", function() { return setKeybindingSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getKeybindingSrv", function() { return getKeybindingSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");
/* harmony import */ var app_store_store__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/store/store */ "./public/app/store/store.ts");
/* harmony import */ var mousetrap__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! mousetrap */ "./node_modules/mousetrap/mousetrap.js");
/* harmony import */ var mousetrap__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(mousetrap__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var mousetrap_global_bind__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! mousetrap-global-bind */ "./node_modules/mousetrap-global-bind/mousetrap-global-bind.js");
/* harmony import */ var mousetrap_global_bind__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(mousetrap_global_bind__WEBPACK_IMPORTED_MODULE_8__);









var KeybindingSrv = /** @class */ (function () {
    /** @ngInject */
    function KeybindingSrv($rootScope, $location, $timeout, datasourceSrv, timeSrv, contextSrv) {
        var _this = this;
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.$timeout = $timeout;
        this.datasourceSrv = datasourceSrv;
        this.timeSrv = timeSrv;
        this.contextSrv = contextSrv;
        this.modalOpen = false;
        this.timepickerOpen = false;
        // clear out all shortcuts on route change
        $rootScope.$on('$routeChangeSuccess', function () {
            mousetrap__WEBPACK_IMPORTED_MODULE_7___default.a.reset();
            // rebind global shortcuts
            _this.setupGlobal();
        });
        this.setupGlobal();
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].on('show-modal', function () { return (_this.modalOpen = true); });
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].on('timepickerOpen', function () { return (_this.timepickerOpen = true); });
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].on('timepickerClosed', function () { return (_this.timepickerOpen = false); });
    }
    KeybindingSrv.prototype.setupGlobal = function () {
        if (!(this.$location.path() === '/login')) {
            this.bind(['?', 'h'], this.showHelpModal);
            this.bind('g h', this.goToHome);
            this.bind('g a', this.openAlerting);
            this.bind('g p', this.goToProfile);
            this.bind('s o', this.openSearch);
            this.bind('f', this.openSearch);
            this.bind('esc', this.exit);
            this.bindGlobal('esc', this.globalEsc);
        }
    };
    KeybindingSrv.prototype.globalEsc = function () {
        var anyDoc = document;
        var activeElement = anyDoc.activeElement;
        // typehead needs to handle it
        var typeaheads = document.querySelectorAll('.slate-typeahead--open');
        if (typeaheads.length > 0) {
            return;
        }
        // second check if we are in an input we can blur
        if (activeElement && activeElement.blur) {
            if (activeElement.nodeName === 'INPUT' ||
                activeElement.nodeName === 'TEXTAREA' ||
                activeElement.hasAttribute('data-slate-editor')) {
                anyDoc.activeElement.blur();
                return;
            }
        }
        // ok no focused input or editor that should block this, let exist!
        this.exit();
    };
    KeybindingSrv.prototype.openSearch = function () {
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('show-dash-search');
    };
    KeybindingSrv.prototype.openAlerting = function () {
        this.$location.url('/alerting');
    };
    KeybindingSrv.prototype.goToHome = function () {
        this.$location.url('/');
    };
    KeybindingSrv.prototype.goToProfile = function () {
        this.$location.url('/profile');
    };
    KeybindingSrv.prototype.showHelpModal = function () {
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('show-modal', { templateHtml: '<help-modal></help-modal>' });
    };
    KeybindingSrv.prototype.exit = function () {
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('hide-modal');
        if (this.modalOpen) {
            this.modalOpen = false;
            return;
        }
        if (this.timepickerOpen) {
            this.$rootScope.appEvent('closeTimepicker');
            this.timepickerOpen = false;
            return;
        }
        // close settings view
        var search = this.$location.search();
        if (search.editview) {
            delete search.editview;
            this.$location.search(search);
            return;
        }
        if (search.fullscreen) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('panel-change-view', { fullscreen: false, edit: false });
            return;
        }
        if (search.kiosk) {
            this.$rootScope.appEvent('toggle-kiosk-mode', { exit: true });
        }
    };
    KeybindingSrv.prototype.bind = function (keyArg, fn) {
        var _this = this;
        mousetrap__WEBPACK_IMPORTED_MODULE_7___default.a.bind(keyArg, function (evt) {
            evt.preventDefault();
            evt.stopPropagation();
            evt.returnValue = false;
            return _this.$rootScope.$apply(fn.bind(_this));
        }, 'keydown');
    };
    KeybindingSrv.prototype.bindGlobal = function (keyArg, fn) {
        var _this = this;
        mousetrap__WEBPACK_IMPORTED_MODULE_7___default.a.bindGlobal(keyArg, function (evt) {
            evt.preventDefault();
            evt.stopPropagation();
            evt.returnValue = false;
            return _this.$rootScope.$apply(fn.bind(_this));
        }, 'keydown');
    };
    KeybindingSrv.prototype.unbind = function (keyArg, keyType) {
        mousetrap__WEBPACK_IMPORTED_MODULE_7___default.a.unbind(keyArg, keyType);
    };
    KeybindingSrv.prototype.showDashEditView = function () {
        var search = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.extend(this.$location.search(), { editview: 'settings' });
        this.$location.search(search);
    };
    KeybindingSrv.prototype.setupDashboardBindings = function (scope, dashboard) {
        var _this = this;
        this.bind('mod+o', function () {
            dashboard.graphTooltip = (dashboard.graphTooltip + 1) % 3;
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('graph-hover-clear');
            dashboard.startRefresh();
        });
        this.bind('mod+s', function () {
            scope.appEvent('save-dashboard');
        });
        this.bind('t z', function () {
            scope.appEvent('zoom-out', 2);
        });
        this.bind('ctrl+z', function () {
            scope.appEvent('zoom-out', 2);
        });
        this.bind('t left', function () {
            scope.appEvent('shift-time', -1);
        });
        this.bind('t right', function () {
            scope.appEvent('shift-time', 1);
        });
        // edit panel
        this.bind('e', function () {
            if (dashboard.meta.focusPanelId && dashboard.meta.canEdit) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('panel-change-view', {
                    fullscreen: true,
                    edit: true,
                    panelId: dashboard.meta.focusPanelId,
                    toggle: true,
                });
            }
        });
        // view panel
        this.bind('v', function () {
            if (dashboard.meta.focusPanelId) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('panel-change-view', {
                    fullscreen: true,
                    panelId: dashboard.meta.focusPanelId,
                    toggle: true,
                });
            }
        });
        // jump to explore if permissions allow
        if (this.contextSrv.hasAccessToExplore()) {
            this.bind('x', function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
                var panel, datasource, url, urlWithoutBase_1;
                var _this = this;
                return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!dashboard.meta.focusPanelId) return [3 /*break*/, 3];
                            panel = dashboard.getPanelById(dashboard.meta.focusPanelId);
                            return [4 /*yield*/, this.datasourceSrv.get(panel.datasource)];
                        case 1:
                            datasource = _a.sent();
                            return [4 /*yield*/, Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__["getExploreUrl"])(panel, panel.targets, datasource, this.datasourceSrv, this.timeSrv)];
                        case 2:
                            url = _a.sent();
                            urlWithoutBase_1 = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_5__["default"].stripBaseFromUrl(url);
                            if (urlWithoutBase_1) {
                                this.$timeout(function () { return _this.$location.url(urlWithoutBase_1); });
                            }
                            _a.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            }); });
        }
        // delete panel
        this.bind('p r', function () {
            if (dashboard.meta.focusPanelId && dashboard.meta.canEdit) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('remove-panel', dashboard.meta.focusPanelId);
                dashboard.meta.focusPanelId = 0;
            }
        });
        // duplicate panel
        this.bind('p d', function () {
            if (dashboard.meta.focusPanelId && dashboard.meta.canEdit) {
                var panelIndex = dashboard.getPanelInfoById(dashboard.meta.focusPanelId).index;
                dashboard.duplicatePanel(dashboard.panels[panelIndex]);
            }
        });
        // share panel
        this.bind('p s', function () {
            if (dashboard.meta.focusPanelId) {
                var shareScope = scope.$new();
                var panelInfo = dashboard.getPanelInfoById(dashboard.meta.focusPanelId);
                shareScope.panel = panelInfo.panel;
                shareScope.dashboard = dashboard;
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('show-modal', {
                    src: 'public/app/features/dashboard/components/ShareModal/template.html',
                    scope: shareScope,
                });
            }
        });
        // toggle panel legend
        this.bind('p l', function () {
            if (dashboard.meta.focusPanelId) {
                var panelInfo = dashboard.getPanelInfoById(dashboard.meta.focusPanelId);
                if (panelInfo.panel.legend) {
                    var panelRef = dashboard.getPanelById(dashboard.meta.focusPanelId);
                    panelRef.legend.show = !panelRef.legend.show;
                    panelRef.render();
                }
            }
        });
        // toggle all panel legends
        this.bind('d l', function () {
            dashboard.toggleLegendsForAll();
        });
        // collapse all rows
        this.bind('d shift+c', function () {
            dashboard.collapseRows();
        });
        // expand all rows
        this.bind('d shift+e', function () {
            dashboard.expandRows();
        });
        this.bind('d n', function () {
            _this.$location.url('/dashboard/new');
        });
        this.bind('d r', function () {
            dashboard.startRefresh();
        });
        this.bind('d s', function () {
            _this.showDashEditView();
        });
        this.bind('d k', function () {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('toggle-kiosk-mode');
        });
        this.bind('d v', function () {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('toggle-view-mode');
        });
        //Autofit panels
        this.bind('d a', function () {
            // this has to be a full page reload
            var queryParams = app_store_store__WEBPACK_IMPORTED_MODULE_6__["store"].getState().location.query;
            var newUrlParam = queryParams.autofitpanels ? '' : '&autofitpanels';
            window.location.href = window.location.href + newUrlParam;
        });
    };
    return KeybindingSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].service('keybindingSrv', KeybindingSrv);
/**
 * Code below exports the service to react components
 */
var singletonInstance;
function setKeybindingSrv(instance) {
    singletonInstance = instance;
}
function getKeybindingSrv() {
    return singletonInstance;
}


/***/ }),

/***/ "./public/app/core/services/ng_react.ts":
/*!**********************************************!*\
  !*** ./public/app/core/services/ng_react.ts ***!
  \**********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_4__);
//
// This is using ng-react with this PR applied https://github.com/ngReact/ngReact/pull/199
//

// # ngReact
// ### Use React Components inside of your Angular applications
//
// Composed of
// - reactComponent (generic directive for delegating off to React Components)
// - reactDirective (factory for creating specific directives that correspond to reactComponent directives)




// get a react component from name (components can be an angular injectable e.g. value, factory or
// available on window
function getReactComponent(name, $injector) {
    // if name is a function assume it is component and return it
    if (angular__WEBPACK_IMPORTED_MODULE_4___default.a.isFunction(name)) {
        return name;
    }
    // a React component name must be specified
    if (!name) {
        throw new Error('ReactComponent name attribute must be specified');
    }
    // ensure the specified React component is accessible, and fail fast if it's not
    var reactComponent;
    try {
        reactComponent = $injector.get(name);
    }
    catch (e) { }
    if (!reactComponent) {
        try {
            reactComponent = name.split('.').reduce(function (current, namePart) {
                // @ts-ignore
                return current[namePart];
            }, window);
        }
        catch (e) { }
    }
    if (!reactComponent) {
        throw Error('Cannot find react component ' + name);
    }
    return reactComponent;
}
// wraps a function with scope.$apply, if already applied just return
function applied(fn, scope) {
    if (fn.wrappedInApply) {
        return fn;
    }
    //tslint:disable-next-line:only-arrow-functions
    var wrapped = function () {
        var args = arguments;
        var phase = scope.$root.$$phase;
        if (phase === '$apply' || phase === '$digest') {
            return fn.apply(null, args);
        }
        else {
            return scope.$apply(function () {
                return fn.apply(null, args);
            });
        }
    };
    wrapped.wrappedInApply = true;
    return wrapped;
}
/**
 * wraps functions on obj in scope.$apply
 *
 * keeps backwards compatibility, as if propsConfig is not passed, it will
 * work as before, wrapping all functions and won't wrap only when specified.
 *
 * @version 0.4.1
 * @param obj react component props
 * @param scope current scope
 * @param propsConfig configuration object for all properties
 * @returns {Object} props with the functions wrapped in scope.$apply
 */
function applyFunctions(obj, scope, propsConfig) {
    return Object.keys(obj || {}).reduce(function (prev, key) {
        var value = obj[key];
        var config = (propsConfig || {})[key] || {};
        /**
         * wrap functions in a function that ensures they are scope.$applied
         * ensures that when function is called from a React component
         * the Angular digest cycle is run
         */
        // @ts-ignore
        prev[key] = angular__WEBPACK_IMPORTED_MODULE_4___default.a.isFunction(value) && config.wrapApply !== false ? applied(value, scope) : value;
        return prev;
    }, {});
}
/**
 *
 * @param watchDepth (value of HTML watch-depth attribute)
 * @param scope (angular scope)
 *
 * Uses the watchDepth attribute to determine how to watch props on scope.
 * If watchDepth attribute is NOT reference or collection, watchDepth defaults to deep watching by value
 */
function watchProps(watchDepth, scope, watchExpressions, listener) {
    var e_1, _a;
    var supportsWatchCollection = angular__WEBPACK_IMPORTED_MODULE_4___default.a.isFunction(scope.$watchCollection);
    var supportsWatchGroup = angular__WEBPACK_IMPORTED_MODULE_4___default.a.isFunction(scope.$watchGroup);
    var watchGroupExpressions = [];
    try {
        for (var watchExpressions_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](watchExpressions), watchExpressions_1_1 = watchExpressions_1.next(); !watchExpressions_1_1.done; watchExpressions_1_1 = watchExpressions_1.next()) {
            var expr = watchExpressions_1_1.value;
            var actualExpr = getPropExpression(expr);
            var exprWatchDepth = getPropWatchDepth(watchDepth, expr);
            // ignore empty expressions & expressions with functions
            if (!actualExpr || actualExpr.match(/\(.*\)/) || exprWatchDepth === 'one-time') {
                continue;
            }
            if (exprWatchDepth === 'collection' && supportsWatchCollection) {
                scope.$watchCollection(actualExpr, listener);
            }
            else if (exprWatchDepth === 'reference' && supportsWatchGroup) {
                watchGroupExpressions.push(actualExpr);
            }
            else {
                scope.$watch(actualExpr, listener, exprWatchDepth !== 'reference');
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (watchExpressions_1_1 && !watchExpressions_1_1.done && (_a = watchExpressions_1.return)) _a.call(watchExpressions_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    if (watchDepth === 'one-time') {
        listener();
    }
    if (watchGroupExpressions.length) {
        scope.$watchGroup(watchGroupExpressions, listener);
    }
}
// render React component, with scope[attrs.props] being passed in as the component props
function renderComponent(component, props, scope, elem) {
    scope.$evalAsync(function () {
        react_dom__WEBPACK_IMPORTED_MODULE_3___default.a.render(react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(component, props), elem[0]);
    });
}
// get prop name from prop (string or array)
function getPropName(prop) {
    return Array.isArray(prop) ? prop[0] : prop;
}
// get prop name from prop (string or array)
function getPropConfig(prop) {
    return Array.isArray(prop) ? prop[1] : {};
}
// get prop expression from prop (string or array)
function getPropExpression(prop) {
    return Array.isArray(prop) ? prop[0] : prop;
}
/**
 * Finds the normalized attribute knowing that React props accept any type of capitalization and it also handles
 * kabab case attributes which can be used in case the attribute would also be a standard html attribute and would be
 * evaluated by the browser as such.
 * @param attrs All attributes of the component.
 * @param propName Name of the prop that react component expects.
 */
function findAttribute(attrs, propName) {
    var index = Object.keys(attrs).find(function (attr) {
        return attr.toLowerCase() === propName.toLowerCase() || attr.toLowerCase() === Object(lodash__WEBPACK_IMPORTED_MODULE_1__["kebabCase"])(propName);
    });
    // @ts-ignore
    return attrs[index];
}
// get watch depth of prop (string or array)
function getPropWatchDepth(defaultWatch, prop) {
    var customWatchDepth = Array.isArray(prop) && angular__WEBPACK_IMPORTED_MODULE_4___default.a.isObject(prop[1]) && prop[1].watchDepth;
    return customWatchDepth || defaultWatch;
}
// # reactComponent
// Directive that allows React components to be used in Angular templates.
//
// Usage:
//     <react-component name="Hello" props="name"/>
//
// This requires that there exists an injectable or globally available 'Hello' React component.
// The 'props' attribute is optional and is passed to the component.
//
// The following would would create and register the component:
//
//     var module = angular.module('ace.react.components');
//     module.value('Hello', React.createClass({
//         render: function() {
//             return <div>Hello {this.props.name}</div>;
//         }
//     }));
//
var reactComponent = function ($injector) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, elem, attrs) {
            var _this = this;
            var reactComponent = getReactComponent(attrs.name, $injector);
            var renderMyComponent = function () {
                var scopeProps = scope.$eval(attrs.props);
                var props = applyFunctions(scopeProps, scope);
                renderComponent(reactComponent, props, scope, elem);
            };
            // If there are props, re-render when they change
            attrs.props ? watchProps(attrs.watchDepth, scope, [attrs.props], renderMyComponent) : renderMyComponent();
            // cleanup when scope is destroyed
            scope.$on('$destroy', function () {
                if (!attrs.onScopeDestroy) {
                    react_dom__WEBPACK_IMPORTED_MODULE_3___default.a.unmountComponentAtNode(elem[0]);
                }
                else {
                    scope.$eval(attrs.onScopeDestroy, {
                        unmountComponent: react_dom__WEBPACK_IMPORTED_MODULE_3___default.a.unmountComponentAtNode.bind(_this, elem[0]),
                    });
                }
            });
        },
    };
};
// # reactDirective
// Factory function to create directives for React components.
//
// With a component like this:
//
//     var module = angular.module('ace.react.components');
//     module.value('Hello', React.createClass({
//         render: function() {
//             return <div>Hello {this.props.name}</div>;
//         }
//     }));
//
// A directive can be created and registered with:
//
//     module.directive('hello', function(reactDirective) {
//         return reactDirective('Hello', ['name']);
//     });
//
// Where the first argument is the injectable or globally accessible name of the React component
// and the second argument is an array of property names to be watched and passed to the React component
// as props.
//
// This directive can then be used like this:
//
//     <hello name="name"/>
//
var reactDirective = function ($injector) {
    return function (reactComponentName, props, conf, injectableProps) {
        var directive = {
            restrict: 'E',
            replace: true,
            link: function (scope, elem, attrs) {
                var _this = this;
                var reactComponent = getReactComponent(reactComponentName, $injector);
                // if props is not defined, fall back to use the React component's propTypes if present
                props = props || Object.keys(reactComponent.propTypes || {});
                // for each of the properties, get their scope value and set it to scope.props
                var renderMyComponent = function () {
                    var scopeProps = {};
                    var config = {};
                    props.forEach(function (prop) {
                        var propName = getPropName(prop);
                        scopeProps[propName] = scope.$eval(findAttribute(attrs, propName));
                        config[propName] = getPropConfig(prop);
                    });
                    scopeProps = applyFunctions(scopeProps, scope, config);
                    scopeProps = angular__WEBPACK_IMPORTED_MODULE_4___default.a.extend({}, scopeProps, injectableProps);
                    renderComponent(reactComponent, scopeProps, scope, elem);
                };
                // watch each property name and trigger an update whenever something changes,
                // to update scope.props with new values
                var propExpressions = props.map(function (prop) {
                    return Array.isArray(prop)
                        ? [findAttribute(attrs, prop[0]), getPropConfig(prop)]
                        : findAttribute(attrs, prop);
                });
                // If we don't have any props, then our watch statement won't fire.
                props.length ? watchProps(attrs.watchDepth, scope, propExpressions, renderMyComponent) : renderMyComponent();
                // cleanup when scope is destroyed
                scope.$on('$destroy', function () {
                    if (!attrs.onScopeDestroy) {
                        react_dom__WEBPACK_IMPORTED_MODULE_3___default.a.unmountComponentAtNode(elem[0]);
                    }
                    else {
                        scope.$eval(attrs.onScopeDestroy, {
                            unmountComponent: react_dom__WEBPACK_IMPORTED_MODULE_3___default.a.unmountComponentAtNode.bind(_this, elem[0]),
                        });
                    }
                });
            },
        };
        return angular__WEBPACK_IMPORTED_MODULE_4___default.a.extend(directive, conf);
    };
};
var ngModule = angular__WEBPACK_IMPORTED_MODULE_4___default.a.module('react', []);
ngModule.directive('reactComponent', ['$injector', reactComponent]);
ngModule.factory('reactDirective', ['$injector', reactDirective]);


/***/ }),

/***/ "./public/app/core/services/popover_srv.ts":
/*!*************************************************!*\
  !*** ./public/app/core/services/popover_srv.ts ***!
  \*************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tether-drop */ "./node_modules/tether-drop/dist/js/drop.js");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tether_drop__WEBPACK_IMPORTED_MODULE_2__);


// @ts-ignore

/** @ngInject */
function popoverSrv($compile, $rootScope, $timeout) {
    var openDrop = null;
    this.close = function () {
        if (openDrop) {
            openDrop.close();
        }
    };
    this.show = function (options) {
        if (openDrop) {
            openDrop.close();
            openDrop = null;
        }
        var scope = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.extend($rootScope.$new(true), options.model);
        var drop;
        var cleanUp = function () {
            setTimeout(function () {
                scope.$destroy();
                if (drop.tether) {
                    drop.destroy();
                }
                if (options.onClose) {
                    options.onClose();
                }
            });
            openDrop = null;
        };
        scope.dismiss = function () {
            drop.close();
        };
        var contentElement = document.createElement('div');
        contentElement.innerHTML = options.template;
        $compile(contentElement)(scope);
        $timeout(function () {
            drop = new tether_drop__WEBPACK_IMPORTED_MODULE_2___default.a({
                target: options.element,
                content: contentElement,
                position: options.position,
                classes: options.classNames || 'drop-popover',
                openOn: options.openOn,
                hoverCloseDelay: 200,
                tetherOptions: {
                    constraints: [{ to: 'scrollParent', attachment: 'together' }],
                },
            });
            drop.on('close', function () {
                cleanUp();
            });
            openDrop = drop;
            openDrop.open();
        }, 100);
        // return close function
        return function () {
            if (drop) {
                drop.close();
            }
        };
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('popoverSrv', popoverSrv);


/***/ }),

/***/ "./public/app/core/services/search_srv.ts":
/*!************************************************!*\
  !*** ./public/app/core/services/search_srv.ts ***!
  \************************************************/
/*! exports provided: SearchSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SearchSrv", function() { return SearchSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/services/impression_srv */ "./public/app/core/services/impression_srv.ts");
/* harmony import */ var app_core_store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/store */ "./public/app/core/store.ts");
/* harmony import */ var app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/services/context_srv */ "./public/app/core/services/context_srv.ts");






var SearchSrv = /** @class */ (function () {
    /** @ngInject */
    function SearchSrv(backendSrv, $q) {
        this.backendSrv = backendSrv;
        this.$q = $q;
        this.recentIsOpen = app_core_store__WEBPACK_IMPORTED_MODULE_4__["default"].getBool('search.sections.recent', true);
        this.starredIsOpen = app_core_store__WEBPACK_IMPORTED_MODULE_4__["default"].getBool('search.sections.starred', true);
    }
    SearchSrv.prototype.getRecentDashboards = function (sections) {
        var _this = this;
        return this.queryForRecentDashboards().then(function (result) {
            if (result.length > 0) {
                sections['recent'] = {
                    title: 'Recent',
                    icon: 'fa fa-clock-o',
                    score: -1,
                    removable: true,
                    expanded: _this.recentIsOpen,
                    toggle: _this.toggleRecent.bind(_this),
                    items: result,
                };
            }
        });
    };
    SearchSrv.prototype.queryForRecentDashboards = function () {
        var dashIds = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.take(app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_3__["default"].getDashboardOpened(), 30);
        if (dashIds.length === 0) {
            return Promise.resolve([]);
        }
        return this.backendSrv.search({ dashboardIds: dashIds }).then(function (result) {
            return dashIds
                .map(function (orderId) {
                return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(result, { id: orderId });
            })
                .filter(function (hit) { return hit && !hit.isStarred; });
        });
    };
    SearchSrv.prototype.toggleRecent = function (section) {
        this.recentIsOpen = section.expanded = !section.expanded;
        app_core_store__WEBPACK_IMPORTED_MODULE_4__["default"].set('search.sections.recent', this.recentIsOpen);
        if (!section.expanded || section.items.length) {
            return Promise.resolve(section);
        }
        return this.queryForRecentDashboards().then(function (result) {
            section.items = result;
            return Promise.resolve(section);
        });
    };
    SearchSrv.prototype.toggleStarred = function (section) {
        this.starredIsOpen = section.expanded = !section.expanded;
        app_core_store__WEBPACK_IMPORTED_MODULE_4__["default"].set('search.sections.starred', this.starredIsOpen);
        return Promise.resolve(section);
    };
    SearchSrv.prototype.getStarred = function (sections) {
        var _this = this;
        if (!app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_5__["contextSrv"].isSignedIn) {
            return Promise.resolve();
        }
        return this.backendSrv.search({ starred: true, limit: 30 }).then(function (result) {
            if (result.length > 0) {
                sections['starred'] = {
                    title: 'Starred',
                    icon: 'fa fa-star-o',
                    score: -2,
                    expanded: _this.starredIsOpen,
                    toggle: _this.toggleStarred.bind(_this),
                    items: result,
                };
            }
        });
    };
    SearchSrv.prototype.search = function (options) {
        var _this = this;
        var sections = {};
        var promises = [];
        var query = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.clone(options);
        var hasFilters = options.query ||
            (options.tag && options.tag.length > 0) ||
            options.starred ||
            (options.folderIds && options.folderIds.length > 0);
        if (!options.skipRecent && !hasFilters) {
            promises.push(this.getRecentDashboards(sections));
        }
        if (!options.skipStarred && !hasFilters) {
            promises.push(this.getStarred(sections));
        }
        query.folderIds = query.folderIds || [];
        if (!hasFilters) {
            query.folderIds = [0];
        }
        promises.push(this.backendSrv.search(query).then(function (results) {
            return _this.handleSearchResult(sections, results);
        }));
        return this.$q.all(promises).then(function () {
            return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.values(sections), 'score');
        });
    };
    SearchSrv.prototype.handleSearchResult = function (sections, results) {
        var e_1, _a, e_2, _b;
        if (results.length === 0) {
            return sections;
        }
        try {
            // create folder index
            for (var results_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](results), results_1_1 = results_1.next(); !results_1_1.done; results_1_1 = results_1.next()) {
                var hit = results_1_1.value;
                if (hit.type === 'dash-folder') {
                    sections[hit.id] = {
                        id: hit.id,
                        uid: hit.uid,
                        title: hit.title,
                        expanded: false,
                        items: [],
                        toggle: this.toggleFolder.bind(this),
                        url: hit.url,
                        icon: 'fa fa-folder',
                        score: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.keys(sections).length,
                    };
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (results_1_1 && !results_1_1.done && (_a = results_1.return)) _a.call(results_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        try {
            for (var results_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](results), results_2_1 = results_2.next(); !results_2_1.done; results_2_1 = results_2.next()) {
                var hit = results_2_1.value;
                if (hit.type === 'dash-folder') {
                    continue;
                }
                var section = sections[hit.folderId || 0];
                if (!section) {
                    if (hit.folderId) {
                        section = {
                            id: hit.folderId,
                            uid: hit.folderUid,
                            title: hit.folderTitle,
                            url: hit.folderUrl,
                            items: [],
                            icon: 'fa fa-folder-open',
                            toggle: this.toggleFolder.bind(this),
                            score: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.keys(sections).length,
                        };
                    }
                    else {
                        section = {
                            id: 0,
                            title: 'General',
                            items: [],
                            icon: 'fa fa-folder-open',
                            toggle: this.toggleFolder.bind(this),
                            score: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.keys(sections).length,
                        };
                    }
                    // add section
                    sections[hit.folderId || 0] = section;
                }
                section.expanded = true;
                section.items.push(hit);
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (results_2_1 && !results_2_1.done && (_b = results_2.return)) _b.call(results_2);
            }
            finally { if (e_2) throw e_2.error; }
        }
    };
    SearchSrv.prototype.toggleFolder = function (section) {
        section.expanded = !section.expanded;
        section.icon = section.expanded ? 'fa fa-folder-open' : 'fa fa-folder';
        if (section.items.length) {
            return Promise.resolve(section);
        }
        var query = {
            folderIds: [section.id],
        };
        return this.backendSrv.search(query).then(function (results) {
            section.items = results;
            return Promise.resolve(section);
        });
    };
    SearchSrv.prototype.getDashboardTags = function () {
        return this.backendSrv.get('/api/dashboards/tags');
    };
    return SearchSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].service('searchSrv', SearchSrv);


/***/ }),

/***/ "./public/app/core/services/segment_srv.ts":
/*!*************************************************!*\
  !*** ./public/app/core/services/segment_srv.ts ***!
  \*************************************************/
/*! exports provided: uiSegmentSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uiSegmentSrv", function() { return uiSegmentSrv; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core_module */ "./public/app/core/core_module.ts");


/** @ngInject */
function uiSegmentSrv($sce, templateSrv) {
    var self = this;
    var MetricSegment = /** @class */ (function () {
        function MetricSegment(options) {
            if (options === '*' || options.value === '*') {
                this.value = '*';
                this.html = $sce.trustAsHtml('<i class="fa fa-asterisk"><i>');
                this.type = options.type;
                this.expandable = true;
                return;
            }
            if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(options)) {
                this.value = options;
                this.html = $sce.trustAsHtml(templateSrv.highlightVariablesAsHtml(this.value));
                return;
            }
            // temp hack to work around legacy inconsistency in segment model
            this.text = options.value;
            this.cssClass = options.cssClass;
            this.custom = options.custom;
            this.type = options.type;
            this.fake = options.fake;
            this.value = options.value;
            this.selectMode = options.selectMode;
            this.type = options.type;
            this.expandable = options.expandable;
            this.html = options.html || $sce.trustAsHtml(templateSrv.highlightVariablesAsHtml(this.value));
        }
        return MetricSegment;
    }());
    this.getSegmentForValue = function (value, fallbackText) {
        if (value) {
            return this.newSegment(value);
        }
        else {
            return this.newSegment({ value: fallbackText, fake: true });
        }
    };
    this.newSelectMeasurement = function () {
        return new MetricSegment({ value: 'select measurement', fake: true });
    };
    this.newFake = function (text, type, cssClass) {
        return new MetricSegment({ value: text, fake: true, type: type, cssClass: cssClass });
    };
    this.newSegment = function (options) {
        return new MetricSegment(options);
    };
    this.newKey = function (key) {
        return new MetricSegment({ value: key, type: 'key', cssClass: 'query-segment-key' });
    };
    this.newKeyValue = function (value) {
        return new MetricSegment({ value: value, type: 'value', cssClass: 'query-segment-value' });
    };
    this.newCondition = function (condition) {
        return new MetricSegment({ value: condition, type: 'condition', cssClass: 'query-keyword' });
    };
    this.newOperator = function (op) {
        return new MetricSegment({ value: op, type: 'operator', cssClass: 'query-segment-operator' });
    };
    this.newOperators = function (ops) {
        return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(ops, function (op) {
            return new MetricSegment({ value: op, type: 'operator', cssClass: 'query-segment-operator' });
        });
    };
    this.transformToSegments = function (addTemplateVars, variableTypeFilter) {
        return function (results) {
            var segments = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(results, function (segment) {
                return self.newSegment({ value: segment.text, expandable: segment.expandable });
            });
            if (addTemplateVars) {
                lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(templateSrv.variables, function (variable) {
                    if (variableTypeFilter === void 0 || variableTypeFilter === variable.type) {
                        segments.unshift(self.newSegment({ type: 'value', value: '$' + variable.name, expandable: true }));
                    }
                });
            }
            return segments;
        };
    };
    this.newSelectMetric = function () {
        return new MetricSegment({ value: 'select metric', fake: true });
    };
    this.newPlusButton = function () {
        return new MetricSegment({
            fake: true,
            html: '<i class="fa fa-plus "></i>',
            type: 'plus-button',
            cssClass: 'query-part',
        });
    };
}
_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('uiSegmentSrv', uiSegmentSrv);


/***/ }),

/***/ "./public/app/core/services/timer.ts":
/*!*******************************************!*\
  !*** ./public/app/core/services/timer.ts ***!
  \*******************************************/
/*! exports provided: Timer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Timer", function() { return Timer; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");


// This service really just tracks a list of $timeout promises to give us a
// method for canceling them all when we need to
var Timer = /** @class */ (function () {
    /** @ngInject */
    function Timer($timeout) {
        this.$timeout = $timeout;
        this.timers = [];
    }
    Timer.prototype.register = function (promise) {
        this.timers.push(promise);
        return promise;
    };
    Timer.prototype.cancel = function (promise) {
        this.timers = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.without(this.timers, promise);
        this.$timeout.cancel(promise);
    };
    Timer.prototype.cancelAll = function () {
        var _this = this;
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(this.timers, function (t) {
            _this.$timeout.cancel(t);
        });
        this.timers = [];
    };
    return Timer;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('timer', Timer);


/***/ }),

/***/ "./public/app/core/services/util_srv.ts":
/*!**********************************************!*\
  !*** ./public/app/core/services/util_srv.ts ***!
  \**********************************************/
/*! exports provided: UtilSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UtilSrv", function() { return UtilSrv; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");


var UtilSrv = /** @class */ (function () {
    /** @ngInject */
    function UtilSrv($rootScope, $modal) {
        this.$rootScope = $rootScope;
        this.$modal = $modal;
    }
    UtilSrv.prototype.init = function () {
        app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].on('show-modal', this.showModal.bind(this), this.$rootScope);
        app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].on('hide-modal', this.hideModal.bind(this), this.$rootScope);
        app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].on('confirm-modal', this.showConfirmModal.bind(this), this.$rootScope);
    };
    UtilSrv.prototype.hideModal = function () {
        if (this.modalScope && this.modalScope.dismiss) {
            this.modalScope.dismiss();
        }
    };
    UtilSrv.prototype.showModal = function (options) {
        if (this.modalScope && this.modalScope.dismiss) {
            this.modalScope.dismiss();
        }
        this.modalScope = options.scope;
        if (options.model) {
            this.modalScope = this.$rootScope.$new();
            this.modalScope.model = options.model;
        }
        else if (!this.modalScope) {
            this.modalScope = this.$rootScope.$new();
        }
        var modal = this.$modal({
            modalClass: options.modalClass,
            template: options.src,
            templateHtml: options.templateHtml,
            persist: false,
            show: false,
            scope: this.modalScope,
            keyboard: false,
            backdrop: options.backdrop,
        });
        Promise.resolve(modal).then(function (modalEl) {
            modalEl.modal('show');
        });
    };
    UtilSrv.prototype.showConfirmModal = function (payload) {
        var scope = this.$rootScope.$new();
        scope.updateConfirmText = function (value) {
            scope.confirmTextValid = payload.confirmText.toLowerCase() === value.toLowerCase();
        };
        scope.title = payload.title;
        scope.text = payload.text;
        scope.text2 = payload.text2;
        scope.text2htmlBind = payload.text2htmlBind;
        scope.confirmText = payload.confirmText;
        scope.onConfirm = payload.onConfirm;
        scope.onAltAction = payload.onAltAction;
        scope.altActionText = payload.altActionText;
        scope.icon = payload.icon || 'fa-check';
        scope.yesText = payload.yesText || 'Yes';
        scope.noText = payload.noText || 'Cancel';
        scope.confirmTextValid = scope.confirmText ? false : true;
        app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].emit('show-modal', {
            src: 'public/app/partials/confirm_modal.html',
            scope: scope,
            modalClass: 'confirm-modal',
        });
    };
    return UtilSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].service('utilSrv', UtilSrv);


/***/ }),

/***/ "./public/app/core/store.ts":
/*!**********************************!*\
  !*** ./public/app/core/store.ts ***!
  \**********************************/
/*! exports provided: Store, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Store", function() { return Store; });
var Store = /** @class */ (function () {
    function Store() {
    }
    Store.prototype.get = function (key) {
        return window.localStorage[key];
    };
    Store.prototype.set = function (key, value) {
        window.localStorage[key] = value;
    };
    Store.prototype.getBool = function (key, def) {
        if (def !== void 0 && !this.exists(key)) {
            return def;
        }
        return window.localStorage[key] === 'true';
    };
    Store.prototype.getObject = function (key, def) {
        var ret = def;
        if (this.exists(key)) {
            var json = window.localStorage[key];
            try {
                ret = JSON.parse(json);
            }
            catch (error) {
                console.error("Error parsing store object: " + key + ". Returning default: " + def + ". [" + error + "]");
            }
        }
        return ret;
    };
    // Returns true when successfully stored
    Store.prototype.setObject = function (key, value) {
        var json;
        try {
            json = JSON.stringify(value);
        }
        catch (error) {
            console.error("Could not stringify object: " + key + ". [" + error + "]");
            return false;
        }
        try {
            this.set(key, json);
        }
        catch (error) {
            // Likely hitting storage quota
            console.error("Could not save item in localStorage: " + key + ". [" + error + "]");
            return false;
        }
        return true;
    };
    Store.prototype.exists = function (key) {
        return window.localStorage[key] !== void 0;
    };
    Store.prototype.delete = function (key) {
        window.localStorage.removeItem(key);
    };
    return Store;
}());

var store = new Store();
/* harmony default export */ __webpack_exports__["default"] = (store);


/***/ }),

/***/ "./public/app/core/table_model.ts":
/*!****************************************!*\
  !*** ./public/app/core/table_model.ts ***!
  \****************************************/
/*! exports provided: default, mergeTablesIntoModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeTablesIntoModel", function() { return mergeTablesIntoModel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


var TableModel = /** @class */ (function () {
    function TableModel(table) {
        var e_1, _a, e_2, _b;
        this.columns = [];
        this.columnMap = {};
        this.rows = [];
        this.type = 'table';
        if (table) {
            if (table.columns) {
                try {
                    for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](table.columns), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var col = _d.value;
                        this.addColumn(col);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
            if (table.rows) {
                try {
                    for (var _e = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](table.rows), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var row = _f.value;
                        this.addRow(row);
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
        }
    }
    TableModel.prototype.sort = function (options) {
        if (options.col === null || this.columns.length <= options.col) {
            return;
        }
        this.rows.sort(function (a, b) {
            a = a[options.col];
            b = b[options.col];
            // Sort null or undefined separately from comparable values
            return +(a == null) - +(b == null) || +(a > b) || -(a < b);
        });
        if (options.desc) {
            this.rows.reverse();
        }
        this.columns[options.col].sort = true;
        this.columns[options.col].desc = options.desc;
    };
    TableModel.prototype.addColumn = function (col) {
        if (!this.columnMap[col.text]) {
            this.columns.push(col);
            this.columnMap[col.text] = col;
        }
    };
    TableModel.prototype.addRow = function (row) {
        this.rows.push(row);
    };
    return TableModel;
}());
/* harmony default export */ __webpack_exports__["default"] = (TableModel);
// Returns true if both rows have matching non-empty fields as well as matching
// indexes where one field is empty and the other is not
function areRowsMatching(columns, row, otherRow) {
    var foundFieldToMatch = false;
    for (var columnIndex = 0; columnIndex < columns.length; columnIndex++) {
        if (row[columnIndex] !== undefined && otherRow[columnIndex] !== undefined) {
            if (row[columnIndex] !== otherRow[columnIndex]) {
                return false;
            }
        }
        else if (row[columnIndex] === undefined || otherRow[columnIndex] === undefined) {
            foundFieldToMatch = true;
        }
    }
    return foundFieldToMatch;
}
function mergeTablesIntoModel(dst) {
    var tables = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        tables[_i - 1] = arguments[_i];
    }
    var model = dst || new TableModel();
    if (arguments.length === 1) {
        return model;
    }
    // Single query returns data columns and rows as is
    if (arguments.length === 2) {
        model.columns = tables[0].hasOwnProperty('columns') ? tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](tables[0].columns) : [];
        model.rows = tables[0].hasOwnProperty('rows') ? tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](tables[0].rows) : [];
        return model;
    }
    // Track column indexes of union: name -> index
    var columnNames = {};
    // Union of all non-value columns
    var columnsUnion = tables.slice().reduce(function (acc, series) {
        series.columns.forEach(function (col) {
            var text = col.text;
            if (columnNames[text] === undefined) {
                columnNames[text] = acc.length;
                acc.push(col);
            }
        });
        return acc;
    }, []);
    // Map old column index to union index per series, e.g.,
    // given columnNames {A: 0, B: 1} and
    // data [{columns: [{ text: 'A' }]}, {columns: [{ text: 'B' }]}] => [[0], [1]]
    var columnIndexMapper = tables.map(function (series) { return series.columns.map(function (col) { return columnNames[col.text]; }); });
    // Flatten rows of all series and adjust new column indexes
    var flattenedRows = tables.reduce(function (acc, series, seriesIndex) {
        var mapper = columnIndexMapper[seriesIndex];
        series.rows.forEach(function (row) {
            var alteredRow = [];
            // Shifting entries according to index mapper
            mapper.forEach(function (to, from) {
                alteredRow[to] = row[from];
            });
            acc.push(alteredRow);
        });
        return acc;
    }, []);
    // Merge rows that have same values for columns
    var mergedRows = {};
    var compactedRows = flattenedRows.reduce(function (acc, row, rowIndex) {
        if (!mergedRows[rowIndex]) {
            // Look from current row onwards
            var offset = rowIndex + 1;
            // More than one row can be merged into current row
            while (offset < flattenedRows.length) {
                // Find next row that could be merged
                var match = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.findIndex(flattenedRows, function (otherRow) { return areRowsMatching(columnsUnion, row, otherRow); }, offset);
                if (match > -1) {
                    var matchedRow = flattenedRows[match];
                    // Merge values from match into current row if there is a gap in the current row
                    for (var columnIndex = 0; columnIndex < columnsUnion.length; columnIndex++) {
                        if (row[columnIndex] === undefined && matchedRow[columnIndex] !== undefined) {
                            row[columnIndex] = matchedRow[columnIndex];
                        }
                    }
                    // Don't visit this row again
                    mergedRows[match] = matchedRow;
                    // Keep looking for more rows to merge
                    offset = match + 1;
                }
                else {
                    // No match found, stop looking
                    break;
                }
            }
            acc.push(row);
        }
        return acc;
    }, []);
    model.columns = columnsUnion;
    model.rows = compactedRows;
    return model;
}


/***/ }),

/***/ "./public/app/core/time_series2.ts":
/*!*****************************************!*\
  !*** ./public/app/core/time_series2.ts ***!
  \*****************************************/
/*! exports provided: updateLegendValues, getDataMinMax, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateLegendValues", function() { return updateLegendValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataMinMax", function() { return getDataMinMax; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/ticks */ "./public/app/core/utils/ticks.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");





function matchSeriesOverride(aliasOrRegex, seriesAlias) {
    if (!aliasOrRegex) {
        return false;
    }
    if (aliasOrRegex[0] === '/') {
        var regex = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["stringToJsRegex"])(aliasOrRegex);
        return seriesAlias.match(regex) != null;
    }
    return aliasOrRegex === seriesAlias;
}
function translateFillOption(fill) {
    return fill === 0 ? 0.001 : fill / 10;
}
/**
 * Calculate decimals for legend and update values for each series.
 * @param data series data
 * @param panel
 * @param height
 */
function updateLegendValues(data, panel, height) {
    for (var i = 0; i < data.length; i++) {
        var series = data[i];
        var yaxes = panel.yaxes;
        var seriesYAxis = series.yaxis || 1;
        var axis = yaxes[seriesYAxis - 1];
        var formatter = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getValueFormat"])(axis.format);
        // decimal override
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNumber(panel.decimals)) {
            series.updateLegendValues(formatter, panel.decimals, null);
        }
        else if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNumber(axis.decimals)) {
            series.updateLegendValues(formatter, axis.decimals + 1, null);
        }
        else {
            // auto decimals
            // legend and tooltip gets one more decimal precision
            // than graph legend ticks
            var _a = getDataMinMax(data), datamin = _a.datamin, datamax = _a.datamax;
            var _b = Object(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_1__["getFlotTickDecimals"])(datamin, datamax, axis, height), tickDecimals = _b.tickDecimals, scaledDecimals = _b.scaledDecimals;
            var tickDecimalsPlusOne = (tickDecimals || -1) + 1;
            series.updateLegendValues(formatter, tickDecimalsPlusOne, scaledDecimals + 2);
        }
    }
}
function getDataMinMax(data) {
    var e_1, _a;
    var datamin = null;
    var datamax = null;
    try {
        for (var data_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
            var series = data_1_1.value;
            if (datamax === null || datamax < series.stats.max) {
                datamax = series.stats.max;
            }
            if (datamin === null || datamin > series.stats.min) {
                datamin = series.stats.min;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return { datamin: datamin, datamax: datamax };
}
/**
 * @deprecated: This class should not be used in new panels
 *
 * Use DataFrame and helpers instead
 */
var TimeSeries = /** @class */ (function () {
    function TimeSeries(opts) {
        this.datapoints = opts.datapoints;
        this.label = opts.alias;
        this.id = opts.alias;
        this.alias = opts.alias;
        this.aliasEscaped = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.escape(opts.alias);
        this.color = opts.color;
        this.bars = { fillColor: opts.color };
        this.valueFormater = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getValueFormat"])('none');
        this.stats = {};
        this.legend = true;
        this.unit = opts.unit;
        this.dataFrameIndex = opts.dataFrameIndex;
        this.fieldIndex = opts.fieldIndex;
        this.hasMsResolution = this.isMsResolutionNeeded();
    }
    TimeSeries.prototype.applySeriesOverrides = function (overrides) {
        this.lines = {};
        this.dashes = {
            dashLength: [],
        };
        this.points = {};
        this.yaxis = 1;
        this.zindex = 0;
        this.nullPointMode = null;
        delete this.stack;
        delete this.bars.show;
        for (var i = 0; i < overrides.length; i++) {
            var override = overrides[i];
            if (!matchSeriesOverride(override.alias, this.alias)) {
                continue;
            }
            if (override.lines !== void 0) {
                this.lines.show = override.lines;
            }
            if (override.dashes !== void 0) {
                this.dashes.show = override.dashes;
                this.lines.lineWidth = 0;
            }
            if (override.points !== void 0) {
                this.points.show = override.points;
            }
            if (override.bars !== void 0) {
                this.bars.show = override.bars;
            }
            if (override.fill !== void 0) {
                this.lines.fill = translateFillOption(override.fill);
            }
            if (override.stack !== void 0) {
                this.stack = override.stack;
            }
            if (override.linewidth !== void 0) {
                this.lines.lineWidth = this.dashes.show ? 0 : override.linewidth;
                this.dashes.lineWidth = override.linewidth;
            }
            if (override.dashLength !== void 0) {
                this.dashes.dashLength[0] = override.dashLength;
            }
            if (override.spaceLength !== void 0) {
                this.dashes.dashLength[1] = override.spaceLength;
            }
            if (override.nullPointMode !== void 0) {
                this.nullPointMode = override.nullPointMode;
            }
            if (override.pointradius !== void 0) {
                this.points.radius = override.pointradius;
            }
            if (override.steppedLine !== void 0) {
                this.lines.steps = override.steppedLine;
            }
            if (override.zindex !== void 0) {
                this.zindex = override.zindex;
            }
            if (override.fillBelowTo !== void 0) {
                this.fillBelowTo = override.fillBelowTo;
            }
            if (override.color !== void 0) {
                this.setColor(override.color);
            }
            if (override.transform !== void 0) {
                this.transform = override.transform;
            }
            if (override.legend !== void 0) {
                this.legend = override.legend;
            }
            if (override.hideTooltip !== void 0) {
                this.hideTooltip = override.hideTooltip;
            }
            if (override.yaxis !== void 0) {
                this.yaxis = override.yaxis;
            }
        }
    };
    TimeSeries.prototype.getFlotPairs = function (fillStyle) {
        var result = [];
        this.stats.total = 0;
        this.stats.max = -Number.MAX_VALUE;
        this.stats.min = Number.MAX_VALUE;
        this.stats.logmin = Number.MAX_VALUE;
        this.stats.avg = null;
        this.stats.current = null;
        this.stats.first = null;
        this.stats.delta = 0;
        this.stats.diff = null;
        this.stats.range = null;
        this.stats.timeStep = Number.MAX_VALUE;
        this.allIsNull = true;
        this.allIsZero = true;
        var ignoreNulls = fillStyle === 'connected';
        var nullAsZero = fillStyle === 'null as zero';
        var currentTime;
        var currentValue;
        var nonNulls = 0;
        var previousTime;
        var previousValue = 0;
        var previousDeltaUp = true;
        for (var i = 0; i < this.datapoints.length; i++) {
            currentValue = this.datapoints[i][0];
            currentTime = this.datapoints[i][1];
            // Due to missing values we could have different timeStep all along the series
            // so we have to find the minimum one (could occur with aggregators such as ZimSum)
            if (previousTime !== undefined) {
                var timeStep = currentTime - previousTime;
                if (timeStep < this.stats.timeStep) {
                    this.stats.timeStep = timeStep;
                }
            }
            previousTime = currentTime;
            if (currentValue === null) {
                if (ignoreNulls) {
                    continue;
                }
                if (nullAsZero) {
                    currentValue = 0;
                }
            }
            if (currentValue !== null) {
                if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNumber(currentValue)) {
                    this.stats.total += currentValue;
                    this.allIsNull = false;
                    nonNulls++;
                }
                if (currentValue > this.stats.max) {
                    this.stats.max = currentValue;
                }
                if (currentValue < this.stats.min) {
                    this.stats.min = currentValue;
                }
                if (this.stats.first === null) {
                    this.stats.first = currentValue;
                }
                else {
                    if (previousValue > currentValue) {
                        // counter reset
                        previousDeltaUp = false;
                        if (i === this.datapoints.length - 1) {
                            // reset on last
                            this.stats.delta += currentValue;
                        }
                    }
                    else {
                        if (previousDeltaUp) {
                            this.stats.delta += currentValue - previousValue; // normal increment
                        }
                        else {
                            this.stats.delta += currentValue; // account for counter reset
                        }
                        previousDeltaUp = true;
                    }
                }
                previousValue = currentValue;
                if (currentValue < this.stats.logmin && currentValue > 0) {
                    this.stats.logmin = currentValue;
                }
                if (currentValue !== 0) {
                    this.allIsZero = false;
                }
            }
            result.push([currentTime, currentValue]);
        }
        if (this.stats.max === -Number.MAX_VALUE) {
            this.stats.max = null;
        }
        if (this.stats.min === Number.MAX_VALUE) {
            this.stats.min = null;
        }
        if (result.length && !this.allIsNull) {
            this.stats.avg = this.stats.total / nonNulls;
            this.stats.current = result[result.length - 1][1];
            if (this.stats.current === null && result.length > 1) {
                this.stats.current = result[result.length - 2][1];
            }
        }
        if (this.stats.max !== null && this.stats.min !== null) {
            this.stats.range = this.stats.max - this.stats.min;
        }
        if (this.stats.current !== null && this.stats.first !== null) {
            this.stats.diff = this.stats.current - this.stats.first;
        }
        this.stats.count = result.length;
        return result;
    };
    TimeSeries.prototype.updateLegendValues = function (formater, decimals, scaledDecimals) {
        this.valueFormater = formater;
        this.decimals = decimals;
        this.scaledDecimals = scaledDecimals;
    };
    TimeSeries.prototype.formatValue = function (value) {
        if (!lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isFinite(value)) {
            value = null; // Prevent NaN formatting
        }
        return this.valueFormater(value, this.decimals, this.scaledDecimals);
    };
    TimeSeries.prototype.isMsResolutionNeeded = function () {
        for (var i = 0; i < this.datapoints.length; i++) {
            if (this.datapoints[i][1] !== null && this.datapoints[i][1] !== undefined) {
                var timestamp = this.datapoints[i][1].toString();
                if (timestamp.length === 13 && timestamp % 1000 !== 0) {
                    return true;
                }
            }
        }
        return false;
    };
    TimeSeries.prototype.hideFromLegend = function (options) {
        if (options.hideEmpty && this.allIsNull) {
            return true;
        }
        // ignore series excluded via override
        if (!this.legend) {
            return true;
        }
        // ignore zero series
        if (options.hideZero && this.allIsZero) {
            return true;
        }
        return false;
    };
    TimeSeries.prototype.setColor = function (color) {
        this.color = color;
        this.bars.fillColor = color;
    };
    return TimeSeries;
}());
/* harmony default export */ __webpack_exports__["default"] = (TimeSeries);


/***/ }),

/***/ "./public/app/core/utils/ConfigProvider.tsx":
/*!**************************************************!*\
  !*** ./public/app/core/utils/ConfigProvider.tsx ***!
  \**************************************************/
/*! exports provided: ConfigContext, ConfigConsumer, provideConfig, getCurrentThemeName, getCurrentTheme, ThemeProvider, provideTheme */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConfigContext", function() { return ConfigContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConfigConsumer", function() { return ConfigConsumer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "provideConfig", function() { return provideConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCurrentThemeName", function() { return getCurrentThemeName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCurrentTheme", function() { return getCurrentTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThemeProvider", function() { return ThemeProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "provideTheme", function() { return provideTheme; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var ConfigContext = react__WEBPACK_IMPORTED_MODULE_1___default.a.createContext(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["config"]);
var ConfigConsumer = ConfigContext.Consumer;
var provideConfig = function (component) {
    var ConfigProvider = function (props) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ConfigContext.Provider, { value: _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["config"] }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(component, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props)))); };
    return ConfigProvider;
};
var getCurrentThemeName = function () {
    return _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["config"].bootData.user.lightTheme ? _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["GrafanaThemeType"].Light : _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["GrafanaThemeType"].Dark;
};
var getCurrentTheme = function () { return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getTheme"])(getCurrentThemeName()); };
var ThemeProvider = function (_a) {
    var children = _a.children;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ConfigConsumer, null, function (config) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["ThemeContext"].Provider, { value: getCurrentTheme() }, children);
    }));
};
var provideTheme = function (component) {
    return provideConfig(function (props) { return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ThemeProvider, null, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(component, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props))); });
};


/***/ }),

/***/ "./public/app/core/utils/UserProvider.tsx":
/*!************************************************!*\
  !*** ./public/app/core/utils/UserProvider.tsx ***!
  \************************************************/
/*! exports provided: UserProvider, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserProvider", function() { return UserProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");




var UserProvider = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UserProvider, _super);
    function UserProvider() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            teams: [],
            orgs: [],
            loadingStates: {
                changePassword: false,
                loadUser: true,
                loadTeams: false,
                loadOrgs: false,
                updateUserProfile: false,
                updateUserOrg: false,
            },
        };
        _this.changePassword = function (payload) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({ loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { changePassword: true }) });
                        return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().put('/api/user/password', payload)];
                    case 1:
                        _a.sent();
                        this.setState({ loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { changePassword: false }) });
                        return [2 /*return*/];
                }
            });
        }); };
        _this.loadUser = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var user;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({
                            loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { loadUser: true }),
                        });
                        return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().get('/api/user')];
                    case 1:
                        user = _a.sent();
                        this.setState({ user: user, loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { loadUser: Object.keys(user).length === 0 }) });
                        return [2 /*return*/];
                }
            });
        }); };
        _this.loadTeams = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var teams;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({
                            loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { loadTeams: true }),
                        });
                        return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().get('/api/user/teams')];
                    case 1:
                        teams = _a.sent();
                        this.setState({ teams: teams, loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { loadTeams: false }) });
                        return [2 /*return*/];
                }
            });
        }); };
        _this.loadOrgs = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var orgs;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({
                            loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { loadOrgs: true }),
                        });
                        return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().get('/api/user/orgs')];
                    case 1:
                        orgs = _a.sent();
                        this.setState({ orgs: orgs, loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { loadOrgs: false }) });
                        return [2 /*return*/];
                }
            });
        }); };
        _this.setUserOrg = function (org) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({
                            loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { updateUserOrg: true }),
                        });
                        return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])()
                                .post('/api/user/using/' + org.orgId, {})
                                .then(function () {
                                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_3__["config"].appSubUrl + '/profile';
                            })
                                .finally(function () {
                                _this.setState({ loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.state.loadingStates, { updateUserOrg: false }) });
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); };
        _this.updateUserProfile = function (payload) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({ loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.loadingStates, { updateUserProfile: true }) });
                        return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])()
                                .put('/api/user', payload)
                                .then(function () {
                                _this.loadUser();
                            })
                                .catch(function (e) { return console.log(e); })
                                .finally(function () {
                                _this.setState({ loadingStates: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.state.loadingStates, { updateUserProfile: false }) });
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); };
        return _this;
    }
    UserProvider.prototype.componentWillMount = function () {
        if (this.props.userId) {
            this.loadUser();
        }
    };
    UserProvider.prototype.render = function () {
        var children = this.props.children;
        var _a = this.state, loadingStates = _a.loadingStates, teams = _a.teams, orgs = _a.orgs, user = _a.user;
        var api = {
            changePassword: this.changePassword,
            loadUser: this.loadUser,
            loadTeams: this.loadTeams,
            loadOrgs: this.loadOrgs,
            updateUserProfile: this.updateUserProfile,
            setUserOrg: this.setUserOrg,
        };
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, children(api, loadingStates, teams, orgs, user));
    };
    return UserProvider;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (UserProvider);


/***/ }),

/***/ "./public/app/core/utils/acl.ts":
/*!**************************************!*\
  !*** ./public/app/core/utils/acl.ts ***!
  \**************************************/
/*! exports provided: processAclItems */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processAclItems", function() { return processAclItems; });
function processAclItems(items) {
    return items.map(processAclItem).sort(function (a, b) { return b.sortRank - a.sortRank || a.name.localeCompare(b.name); });
}
function processAclItem(dto) {
    var item = dto;
    item.sortRank = 0;
    if (item.userId > 0) {
        item.name = item.userLogin;
        item.sortRank = 10;
    }
    else if (item.teamId > 0) {
        item.name = item.team;
        item.sortRank = 20;
    }
    else if (item.role) {
        item.icon = 'fa fa-fw fa-street-view';
        item.name = item.role;
        item.sortRank = 30;
        if (item.role === 'Editor') {
            item.sortRank += 1;
        }
    }
    if (item.inherited) {
        item.sortRank += 100;
    }
    return item;
}


/***/ }),

/***/ "./public/app/core/utils/colors.ts":
/*!*****************************************!*\
  !*** ./public/app/core/utils/colors.ts ***!
  \*****************************************/
/*! exports provided: getThemeColor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getThemeColor", function() { return getThemeColor; });
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");

function getThemeColor(dark, light) {
    return app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData.user.lightTheme ? light : dark;
}


/***/ }),

/***/ "./public/app/core/utils/connectWithReduxStore.tsx":
/*!*********************************************************!*\
  !*** ./public/app/core/utils/connectWithReduxStore.tsx ***!
  \*********************************************************/
/*! exports provided: connectWithStore */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "connectWithStore", function() { return connectWithStore; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var _store_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../store/store */ "./public/app/store/store.ts");




function connectWithStore(WrappedComponent) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    var ConnectedWrappedComponent = react_redux__WEBPACK_IMPORTED_MODULE_2__["connect"].apply(void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](args))(WrappedComponent);
    return function (props) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(ConnectedWrappedComponent, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props, { store: _store_store__WEBPACK_IMPORTED_MODULE_3__["store"] }));
    };
}


/***/ }),

/***/ "./public/app/core/utils/dag.ts":
/*!**************************************!*\
  !*** ./public/app/core/utils/dag.ts ***!
  \**************************************/
/*! exports provided: Edge, Node, Graph, printGraph */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Edge", function() { return Edge; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Node", function() { return Node; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Graph", function() { return Graph; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printGraph", function() { return printGraph; });
var Edge = /** @class */ (function () {
    function Edge() {
    }
    Edge.prototype._linkTo = function (node, direction) {
        if (direction <= 0) {
            node.inputEdges.push(this);
        }
        if (direction >= 0) {
            node.outputEdges.push(this);
        }
        node.edges.push(this);
    };
    Edge.prototype.link = function (inputNode, outputNode) {
        if (!inputNode) {
            throw Error('inputNode is required');
        }
        if (!outputNode) {
            throw Error('outputNode is required');
        }
        this.unlink();
        this.inputNode = inputNode;
        this.outputNode = outputNode;
        this._linkTo(inputNode, 1);
        this._linkTo(outputNode, -1);
        return this;
    };
    Edge.prototype.unlink = function () {
        var pos;
        var inode = this.inputNode;
        var onode = this.outputNode;
        if (!(inode && onode)) {
            return;
        }
        pos = inode.edges.indexOf(this);
        if (pos > -1) {
            inode.edges.splice(pos, 1);
        }
        pos = onode.edges.indexOf(this);
        if (pos > -1) {
            onode.edges.splice(pos, 1);
        }
        pos = inode.outputEdges.indexOf(this);
        if (pos > -1) {
            inode.outputEdges.splice(pos, 1);
        }
        pos = onode.inputEdges.indexOf(this);
        if (pos > -1) {
            onode.inputEdges.splice(pos, 1);
        }
        this.inputNode = null;
        this.outputNode = null;
    };
    return Edge;
}());

var Node = /** @class */ (function () {
    function Node(name) {
        this.name = name;
        this.edges = [];
        this.inputEdges = [];
        this.outputEdges = [];
    }
    Node.prototype.getEdgeFrom = function (from) {
        if (!from) {
            return null;
        }
        if (typeof from === 'object') {
            return this.inputEdges.find(function (e) { return e.inputNode.name === from.name; });
        }
        return this.inputEdges.find(function (e) { return e.inputNode.name === from; });
    };
    Node.prototype.getEdgeTo = function (to) {
        if (!to) {
            return null;
        }
        if (typeof to === 'object') {
            return this.outputEdges.find(function (e) { return e.outputNode.name === to.name; });
        }
        return this.outputEdges.find(function (e) { return e.outputNode.name === to; });
    };
    Node.prototype.getOptimizedInputEdges = function () {
        var _this = this;
        var toBeRemoved = [];
        this.inputEdges.forEach(function (e) {
            var inputEdgesNodes = e.inputNode.inputEdges.map(function (e) { return e.inputNode; });
            inputEdgesNodes.forEach(function (n) {
                var edgeToRemove = n.getEdgeTo(_this.name);
                if (edgeToRemove) {
                    toBeRemoved.push(edgeToRemove);
                }
            });
        });
        return this.inputEdges.filter(function (e) { return toBeRemoved.indexOf(e) === -1; });
    };
    return Node;
}());

var Graph = /** @class */ (function () {
    function Graph() {
        this.nodes = {};
    }
    Graph.prototype.createNode = function (name) {
        var n = new Node(name);
        this.nodes[name] = n;
        return n;
    };
    Graph.prototype.createNodes = function (names) {
        var _this = this;
        var nodes = [];
        names.forEach(function (name) {
            nodes.push(_this.createNode(name));
        });
        return nodes;
    };
    Graph.prototype.link = function (input, output) {
        var _this = this;
        var inputArr = [];
        var outputArr = [];
        var inputNodes = [];
        var outputNodes = [];
        if (input instanceof Array) {
            inputArr = input;
        }
        else {
            inputArr = [input];
        }
        if (output instanceof Array) {
            outputArr = output;
        }
        else {
            outputArr = [output];
        }
        for (var n = 0; n < inputArr.length; n++) {
            var i = inputArr[n];
            if (typeof i === 'string') {
                var n_1 = this.getNode(i);
                if (!n_1) {
                    throw Error("cannot link input node named " + i + " since it doesn't exist in graph");
                }
                inputNodes.push(n_1);
            }
            else {
                inputNodes.push(i);
            }
        }
        for (var n = 0; n < outputArr.length; n++) {
            var i = outputArr[n];
            if (typeof i === 'string') {
                var n_2 = this.getNode(i);
                if (!n_2) {
                    throw Error("cannot link output node named " + i + " since it doesn't exist in graph");
                }
                outputNodes.push(n_2);
            }
            else {
                outputNodes.push(i);
            }
        }
        var edges = [];
        inputNodes.forEach(function (input) {
            outputNodes.forEach(function (output) {
                edges.push(_this.createEdge().link(input, output));
            });
        });
        return edges;
    };
    Graph.prototype.createEdge = function () {
        return new Edge();
    };
    Graph.prototype.getNode = function (name) {
        return this.nodes[name];
    };
    return Graph;
}());

var printGraph = function (g) {
    Object.keys(g.nodes).forEach(function (name) {
        var n = g.nodes[name];
        var outputEdges = n.outputEdges.map(function (e) { return e.outputNode.name; }).join(', ');
        if (!outputEdges) {
            outputEdges = '<none>';
        }
        var inputEdges = n.inputEdges.map(function (e) { return e.inputNode.name; }).join(', ');
        if (!inputEdges) {
            inputEdges = '<none>';
        }
        console.log(n.name + ":\n - links to:   " + outputEdges + "\n - links from: " + inputEdges);
    });
};


/***/ }),

/***/ "./public/app/core/utils/emitter.ts":
/*!******************************************!*\
  !*** ./public/app/core/utils/emitter.ts ***!
  \******************************************/
/*! exports provided: Emitter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Emitter", function() { return Emitter; });
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_0__);

var Emitter = /** @class */ (function () {
    function Emitter() {
        this.emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_0__["EventEmitter"]();
    }
    Emitter.prototype.emit = function (name, data) {
        this.emitter.emit(name, data);
    };
    Emitter.prototype.on = function (name, handler, scope) {
        var _this = this;
        this.emitter.on(name, handler);
        if (scope) {
            var unbind_1 = scope.$on('$destroy', function () {
                _this.emitter.off(name, handler);
                unbind_1();
            });
        }
    };
    Emitter.prototype.removeAllListeners = function (evt) {
        this.emitter.removeAllListeners(evt);
    };
    Emitter.prototype.off = function (name, handler) {
        this.emitter.off(name, handler);
    };
    Emitter.prototype.getEventCount = function () {
        return this.emitter._eventsCount;
    };
    return Emitter;
}());



/***/ }),

/***/ "./public/app/core/utils/errors.ts":
/*!*****************************************!*\
  !*** ./public/app/core/utils/errors.ts ***!
  \*****************************************/
/*! exports provided: getMessageFromError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMessageFromError", function() { return getMessageFromError; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

function getMessageFromError(err) {
    if (err && !lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(err)) {
        if (err.message) {
            return err.message;
        }
        else if (err.data && err.data.message) {
            return err.data.message;
        }
        else if (err.statusText) {
            return err.statusText;
        }
        else {
            return JSON.stringify(err);
        }
    }
    return err;
}


/***/ }),

/***/ "./public/app/core/utils/explore.ts":
/*!******************************************!*\
  !*** ./public/app/core/utils/explore.ts ***!
  \******************************************/
/*! exports provided: DEFAULT_RANGE, DEFAULT_UI_STATE, LAST_USED_DATASOURCE_KEY, lastUsedDatasourceKeyForOrgId, getExploreUrl, buildQueryTransaction, clearQueryKeys, safeParseJson, safeStringifyValue, parseUrlState, serializeStateToUrlParam, generateKey, generateEmptyQuery, generateNewKeyAndAddRefIdIfMissing, ensureQueries, hasNonEmptyQuery, updateHistory, clearHistory, getQueryKeys, getTimeRange, getTimeRangeFromUrl, getValueWithRefId, getFirstQueryErrorWithoutRefId, getRefIds, sortInAscendingOrder, SortOrder, refreshIntervalToSortOrder, sortLogsResult, convertToWebSocketUrl, stopQueryState, getIntervals */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_RANGE", function() { return DEFAULT_RANGE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_UI_STATE", function() { return DEFAULT_UI_STATE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LAST_USED_DATASOURCE_KEY", function() { return LAST_USED_DATASOURCE_KEY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lastUsedDatasourceKeyForOrgId", function() { return lastUsedDatasourceKeyForOrgId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getExploreUrl", function() { return getExploreUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildQueryTransaction", function() { return buildQueryTransaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearQueryKeys", function() { return clearQueryKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "safeParseJson", function() { return safeParseJson; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "safeStringifyValue", function() { return safeStringifyValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseUrlState", function() { return parseUrlState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serializeStateToUrlParam", function() { return serializeStateToUrlParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateKey", function() { return generateKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateEmptyQuery", function() { return generateEmptyQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateNewKeyAndAddRefIdIfMissing", function() { return generateNewKeyAndAddRefIdIfMissing; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ensureQueries", function() { return ensureQueries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasNonEmptyQuery", function() { return hasNonEmptyQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHistory", function() { return updateHistory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearHistory", function() { return clearHistory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getQueryKeys", function() { return getQueryKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeRange", function() { return getTimeRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeRangeFromUrl", function() { return getTimeRangeFromUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValueWithRefId", function() { return getValueWithRefId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFirstQueryErrorWithoutRefId", function() { return getFirstQueryErrorWithoutRefId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRefIds", function() { return getRefIds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortInAscendingOrder", function() { return sortInAscendingOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SortOrder", function() { return SortOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refreshIntervalToSortOrder", function() { return refreshIntervalToSortOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortLogsResult", function() { return sortLogsResult; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToWebSocketUrl", function() { return convertToWebSocketUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stopQueryState", function() { return stopQueryState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getIntervals", function() { return getIntervals; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui_src_components_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui/src/components/RefreshPicker/RefreshPicker */ "./packages/grafana-ui/src/components/RefreshPicker/RefreshPicker.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/url */ "./public/app/core/utils/url.ts");
/* harmony import */ var app_core_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/store */ "./public/app/core/store.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./query */ "./public/app/core/utils/query.ts");
/* harmony import */ var app_types_explore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/types/explore */ "./public/app/types/explore.ts");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../config */ "./public/app/core/config.ts");

// Libraries


// Services & Utils







var DEFAULT_RANGE = {
    from: 'now-1h',
    to: 'now',
};
var DEFAULT_UI_STATE = {
    showingTable: true,
    showingGraph: true,
    showingLogs: true,
    dedupStrategy: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["LogsDedupStrategy"].none,
};
var MAX_HISTORY_ITEMS = 100;
var LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
var lastUsedDatasourceKeyForOrgId = function (orgId) { return LAST_USED_DATASOURCE_KEY + "." + orgId; };
/**
 * Returns an Explore-URL that contains a panel's queries and the dashboard time range.
 *
 * @param panelTargets The origin panel's query targets
 * @param panelDatasource The origin panel's datasource
 * @param datasourceSrv Datasource service to query other datasources in case the panel datasource is mixed
 * @param timeSrv Time service to get the current dashboard range from
 */
function getExploreUrl(panel, panelTargets, panelDatasource, datasourceSrv, timeSrv) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
        var exploreDatasource, exploreTargets, url, _loop_1, exploreTargets_1, exploreTargets_1_1, t, state_1, e_1_1, range, state, exploreState, finalUrl;
        var e_1, _a;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
            switch (_b.label) {
                case 0:
                    exploreDatasource = panelDatasource;
                    exploreTargets = panelTargets;
                    if (!(panelDatasource.meta.id === 'mixed' && exploreTargets)) return [3 /*break*/, 8];
                    _loop_1 = function (t) {
                        var datasource;
                        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, datasourceSrv.get(t.datasource)];
                                case 1:
                                    datasource = _a.sent();
                                    if (datasource) {
                                        exploreDatasource = datasource;
                                        exploreTargets = panelTargets.filter(function (t) { return t.datasource === datasource.name; });
                                        return [2 /*return*/, "break"];
                                    }
                                    return [2 /*return*/];
                            }
                        });
                    };
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 6, 7, 8]);
                    exploreTargets_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](exploreTargets), exploreTargets_1_1 = exploreTargets_1.next();
                    _b.label = 2;
                case 2:
                    if (!!exploreTargets_1_1.done) return [3 /*break*/, 5];
                    t = exploreTargets_1_1.value;
                    return [5 /*yield**/, _loop_1(t)];
                case 3:
                    state_1 = _b.sent();
                    if (state_1 === "break")
                        return [3 /*break*/, 5];
                    _b.label = 4;
                case 4:
                    exploreTargets_1_1 = exploreTargets_1.next();
                    return [3 /*break*/, 2];
                case 5: return [3 /*break*/, 8];
                case 6:
                    e_1_1 = _b.sent();
                    e_1 = { error: e_1_1 };
                    return [3 /*break*/, 8];
                case 7:
                    try {
                        if (exploreTargets_1_1 && !exploreTargets_1_1.done && (_a = exploreTargets_1.return)) _a.call(exploreTargets_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7 /*endfinally*/];
                case 8:
                    if (exploreDatasource) {
                        range = timeSrv.timeRangeForUrl();
                        state = { range: range };
                        if (exploreDatasource.getExploreState) {
                            state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, exploreDatasource.getExploreState(exploreTargets));
                        }
                        else {
                            state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasource: exploreDatasource.name, queries: exploreTargets.map(function (t) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, t, { datasource: exploreDatasource.name })); }) });
                        }
                        exploreState = JSON.stringify(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { originPanelId: panel.id }));
                        url = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__["renderUrl"])('/explore', { left: exploreState });
                    }
                    finalUrl = _config__WEBPACK_IMPORTED_MODULE_9__["config"].appSubUrl + url;
                    return [2 /*return*/, finalUrl];
            }
        });
    });
}
function buildQueryTransaction(queries, queryOptions, range, scanning) {
    var configuredQueries = queries.map(function (query) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query, queryOptions)); });
    var key = queries.reduce(function (combinedKey, query) {
        combinedKey += query.key;
        return combinedKey;
    }, '');
    var _a = getIntervals(range, queryOptions.minInterval, queryOptions.maxDataPoints), interval = _a.interval, intervalMs = _a.intervalMs;
    // Most datasource is using `panelId + query.refId` for cancellation logic.
    // Using `format` here because it relates to the view panel that the request is for.
    // However, some datasources don't use `panelId + query.refId`, but only `panelId`.
    // Therefore panel id has to be unique.
    var panelId = "" + key;
    var request = {
        dashboardId: 0,
        // TODO probably should be taken from preferences but does not seem to be used anyway.
        timezone: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["DefaultTimeZone"],
        startTime: Date.now(),
        interval: interval,
        intervalMs: intervalMs,
        // TODO: the query request expects number and we are using string here. Seems like it works so far but can create
        // issues down the road.
        panelId: panelId,
        targets: configuredQueries,
        range: range,
        requestId: 'explore',
        rangeRaw: range.raw,
        scopedVars: {
            __interval: { text: interval, value: interval },
            __interval_ms: { text: intervalMs, value: intervalMs },
        },
        maxDataPoints: queryOptions.maxDataPoints,
    };
    return {
        queries: queries,
        request: request,
        scanning: scanning,
        id: generateKey(),
        done: false,
        latency: 0,
    };
}
var clearQueryKeys = function (_a) {
    var key = _a.key, refId = _a.refId, rest = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["key", "refId"]);
    return rest;
};
var isSegment = function (segment) {
    var props = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        props[_i - 1] = arguments[_i];
    }
    return props.some(function (prop) { return segment.hasOwnProperty(prop); });
};
var ParseUrlStateIndex;
(function (ParseUrlStateIndex) {
    ParseUrlStateIndex[ParseUrlStateIndex["RangeFrom"] = 0] = "RangeFrom";
    ParseUrlStateIndex[ParseUrlStateIndex["RangeTo"] = 1] = "RangeTo";
    ParseUrlStateIndex[ParseUrlStateIndex["Datasource"] = 2] = "Datasource";
    ParseUrlStateIndex[ParseUrlStateIndex["SegmentsStart"] = 3] = "SegmentsStart";
})(ParseUrlStateIndex || (ParseUrlStateIndex = {}));
var ParseUiStateIndex;
(function (ParseUiStateIndex) {
    ParseUiStateIndex[ParseUiStateIndex["Graph"] = 0] = "Graph";
    ParseUiStateIndex[ParseUiStateIndex["Logs"] = 1] = "Logs";
    ParseUiStateIndex[ParseUiStateIndex["Table"] = 2] = "Table";
    ParseUiStateIndex[ParseUiStateIndex["Strategy"] = 3] = "Strategy";
})(ParseUiStateIndex || (ParseUiStateIndex = {}));
var safeParseJson = function (text) {
    if (!text) {
        return;
    }
    try {
        return JSON.parse(decodeURI(text));
    }
    catch (error) {
        console.error(error);
    }
};
var safeStringifyValue = function (value, space) {
    if (!value) {
        return '';
    }
    try {
        return JSON.stringify(value, null, space);
    }
    catch (error) {
        console.error(error);
    }
    return '';
};
function parseUrlState(initial) {
    var parsed = safeParseJson(initial);
    var errorResult = {
        datasource: null,
        queries: [],
        range: DEFAULT_RANGE,
        ui: DEFAULT_UI_STATE,
        mode: null,
        originPanelId: null,
    };
    if (!parsed) {
        return errorResult;
    }
    if (!Array.isArray(parsed)) {
        return parsed;
    }
    if (parsed.length <= ParseUrlStateIndex.SegmentsStart) {
        console.error('Error parsing compact URL state for Explore.');
        return errorResult;
    }
    var range = {
        from: parsed[ParseUrlStateIndex.RangeFrom],
        to: parsed[ParseUrlStateIndex.RangeTo],
    };
    var datasource = parsed[ParseUrlStateIndex.Datasource];
    var parsedSegments = parsed.slice(ParseUrlStateIndex.SegmentsStart);
    var metricProperties = ['expr', 'target', 'datasource', 'query'];
    var queries = parsedSegments.filter(function (segment) { return isSegment.apply(void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([segment], metricProperties)); });
    var modeObj = parsedSegments.filter(function (segment) { return isSegment(segment, 'mode'); })[0];
    var mode = modeObj ? modeObj.mode : app_types_explore__WEBPACK_IMPORTED_MODULE_8__["ExploreMode"].Metrics;
    var uiState = parsedSegments.filter(function (segment) { return isSegment(segment, 'ui'); })[0];
    var ui = uiState
        ? {
            showingGraph: uiState.ui[ParseUiStateIndex.Graph],
            showingLogs: uiState.ui[ParseUiStateIndex.Logs],
            showingTable: uiState.ui[ParseUiStateIndex.Table],
            dedupStrategy: uiState.ui[ParseUiStateIndex.Strategy],
        }
        : DEFAULT_UI_STATE;
    var originPanelId = parsedSegments.filter(function (segment) { return isSegment(segment, 'originPanelId'); })[0];
    return { datasource: datasource, queries: queries, range: range, ui: ui, mode: mode, originPanelId: originPanelId };
}
function serializeStateToUrlParam(urlState, compact) {
    if (compact) {
        return JSON.stringify(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([
            urlState.range.from,
            urlState.range.to,
            urlState.datasource
        ], urlState.queries, [
            { mode: urlState.mode },
            {
                ui: [
                    !!urlState.ui.showingGraph,
                    !!urlState.ui.showingLogs,
                    !!urlState.ui.showingTable,
                    urlState.ui.dedupStrategy,
                ],
            },
        ]));
    }
    return JSON.stringify(urlState);
}
function generateKey(index) {
    if (index === void 0) { index = 0; }
    return "Q-" + Date.now() + "-" + Math.random() + "-" + index;
}
function generateEmptyQuery(queries, index) {
    if (index === void 0) { index = 0; }
    return { refId: Object(_query__WEBPACK_IMPORTED_MODULE_7__["getNextRefIdChar"])(queries), key: generateKey(index) };
}
var generateNewKeyAndAddRefIdIfMissing = function (target, queries, index) {
    if (index === void 0) { index = 0; }
    var key = generateKey(index);
    var refId = target.refId || Object(_query__WEBPACK_IMPORTED_MODULE_7__["getNextRefIdChar"])(queries);
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, target, { refId: refId, key: key });
};
/**
 * Ensure at least one target exists and that targets have the necessary keys
 */
function ensureQueries(queries) {
    if (queries && typeof queries === 'object' && queries.length > 0) {
        var allQueries = [];
        for (var index = 0; index < queries.length; index++) {
            var query = queries[index];
            var key = generateKey(index);
            var refId = query.refId;
            if (!refId) {
                refId = Object(_query__WEBPACK_IMPORTED_MODULE_7__["getNextRefIdChar"])(allQueries);
            }
            allQueries.push(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query, { refId: refId,
                key: key }));
        }
        return allQueries;
    }
    return [tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, generateEmptyQuery(queries))];
}
/**
 * A target is non-empty when it has keys (with non-empty values) other than refId, key and context.
 */
var validKeys = ['refId', 'key', 'context'];
function hasNonEmptyQuery(queries) {
    return (queries &&
        queries.some(function (query) {
            var keys = Object.keys(query)
                .filter(function (key) { return validKeys.indexOf(key) === -1; })
                .map(function (k) { return query[k]; })
                .filter(function (v) { return v; });
            return keys.length > 0;
        }));
}
/**
 * Update the query history. Side-effect: store history in local storage
 */
function updateHistory(history, datasourceId, queries) {
    var ts = Date.now();
    queries.forEach(function (query) {
        history = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([{ query: query, ts: ts }], history);
    });
    if (history.length > MAX_HISTORY_ITEMS) {
        history = history.slice(0, MAX_HISTORY_ITEMS);
    }
    // Combine all queries of a datasource type into one history
    var historyKey = "grafana.explore.history." + datasourceId;
    app_core_store__WEBPACK_IMPORTED_MODULE_5__["default"].setObject(historyKey, history);
    return history;
}
function clearHistory(datasourceId) {
    var historyKey = "grafana.explore.history." + datasourceId;
    app_core_store__WEBPACK_IMPORTED_MODULE_5__["default"].delete(historyKey);
}
var getQueryKeys = function (queries, datasourceInstance) {
    var queryKeys = queries.reduce(function (newQueryKeys, query, index) {
        var primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
        return newQueryKeys.concat(primaryKey + "-" + index);
    }, []);
    return queryKeys;
};
var getTimeRange = function (timeZone, rawRange) {
    return {
        from: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(rawRange.from, false, timeZone),
        to: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(rawRange.to, true, timeZone),
        raw: rawRange,
    };
};
var parseRawTime = function (value) {
    if (value === null) {
        return null;
    }
    if (value.indexOf('now') !== -1) {
        return value;
    }
    if (value.length === 8) {
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(value, 'YYYYMMDD');
    }
    if (value.length === 15) {
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(value, 'YYYYMMDDTHHmmss');
    }
    // Backward compatibility
    if (value.length === 19) {
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(value, 'YYYY-MM-DD HH:mm:ss');
    }
    if (!isNaN(value)) {
        var epoch = parseInt(value, 10);
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(epoch);
    }
    return null;
};
var getTimeRangeFromUrl = function (range, timeZone) {
    var raw = {
        from: parseRawTime(range.from),
        to: parseRawTime(range.to),
    };
    return {
        from: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(raw.from, false, timeZone),
        to: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(raw.to, true, timeZone),
        raw: raw,
    };
};
var getValueWithRefId = function (value) {
    if (!value) {
        return null;
    }
    if (typeof value !== 'object') {
        return null;
    }
    if (value.refId) {
        return value;
    }
    var keys = Object.keys(value);
    for (var index = 0; index < keys.length; index++) {
        var key = keys[index];
        var refId = getValueWithRefId(value[key]);
        if (refId) {
            return refId;
        }
    }
    return null;
};
var getFirstQueryErrorWithoutRefId = function (errors) {
    if (!errors) {
        return null;
    }
    return errors.filter(function (error) { return (error && error.refId ? false : true); })[0];
};
var getRefIds = function (value) {
    if (!value) {
        return [];
    }
    if (typeof value !== 'object') {
        return [];
    }
    var keys = Object.keys(value);
    var refIds = [];
    for (var index = 0; index < keys.length; index++) {
        var key = keys[index];
        if (key === 'refId') {
            refIds.push(value[key]);
            continue;
        }
        refIds.push(getRefIds(value[key]));
    }
    return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.uniq(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.flatten(refIds));
};
var sortInAscendingOrder = function (a, b) {
    if (a.timestamp < b.timestamp) {
        return -1;
    }
    if (a.timestamp > b.timestamp) {
        return 1;
    }
    return 0;
};
var sortInDescendingOrder = function (a, b) {
    if (a.timestamp > b.timestamp) {
        return -1;
    }
    if (a.timestamp < b.timestamp) {
        return 1;
    }
    return 0;
};
var SortOrder;
(function (SortOrder) {
    SortOrder["Descending"] = "Descending";
    SortOrder["Ascending"] = "Ascending";
})(SortOrder || (SortOrder = {}));
var refreshIntervalToSortOrder = function (refreshInterval) {
    return Object(_grafana_ui_src_components_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_2__["isLive"])(refreshInterval) ? SortOrder.Ascending : SortOrder.Descending;
};
var sortLogsResult = function (logsResult, sortOrder) {
    var rows = logsResult ? logsResult.rows : [];
    sortOrder === SortOrder.Ascending ? rows.sort(sortInAscendingOrder) : rows.sort(sortInDescendingOrder);
    var result = logsResult ? tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, logsResult, { rows: rows }) : { hasUniqueLabels: false, rows: rows };
    return result;
};
var convertToWebSocketUrl = function (url) {
    var protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
    var backend = "" + protocol + window.location.host + _config__WEBPACK_IMPORTED_MODULE_9__["config"].appSubUrl;
    if (backend.endsWith('/')) {
        backend = backend.slice(0, backend.length - 1);
    }
    return "" + backend + url;
};
var stopQueryState = function (querySubscription) {
    if (querySubscription) {
        querySubscription.unsubscribe();
    }
};
function getIntervals(range, lowLimit, resolution) {
    if (!resolution) {
        return { interval: '1s', intervalMs: 1000 };
    }
    return app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_6__["default"].calculateInterval(range, resolution, lowLimit);
}


/***/ }),

/***/ "./public/app/core/utils/factors.ts":
/*!******************************************!*\
  !*** ./public/app/core/utils/factors.ts ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getFactors; });
// Returns the factors of a number
// Example getFactors(12) -> [1, 2, 3, 4, 6, 12]
function getFactors(num) {
    return Array.from(new Array(num + 1), function (_, i) { return i; }).filter(function (i) { return num % i === 0; });
}


/***/ }),

/***/ "./public/app/core/utils/file_export.ts":
/*!**********************************************!*\
  !*** ./public/app/core/utils/file_export.ts ***!
  \**********************************************/
/*! exports provided: convertSeriesListToCsv, exportSeriesListToCsv, convertSeriesListToCsvColumns, exportSeriesListToCsvColumns, convertTableDataToCsv, exportTableDataToCsv, saveSaveBlob */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertSeriesListToCsv", function() { return convertSeriesListToCsv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportSeriesListToCsv", function() { return exportSeriesListToCsv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertSeriesListToCsvColumns", function() { return convertSeriesListToCsvColumns; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportSeriesListToCsvColumns", function() { return exportSeriesListToCsvColumns; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertTableDataToCsv", function() { return convertTableDataToCsv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportTableDataToCsv", function() { return exportTableDataToCsv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveSaveBlob", function() { return saveSaveBlob; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! file-saver */ "./node_modules/file-saver/FileSaver.js");
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! util */ "./node_modules/node-libs-browser/node_modules/util/util.js");
/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");





var DEFAULT_DATETIME_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ';
var POINT_TIME_INDEX = 1;
var POINT_VALUE_INDEX = 0;
var END_COLUMN = ';';
var END_ROW = '\r\n';
var QUOTE = '"';
var EXPORT_FILENAME = 'grafana_data_export.csv';
var defaultOptions = {
    dateTimeFormat: DEFAULT_DATETIME_FORMAT,
    excel: false,
    timezone: '',
};
function csvEscaped(text) {
    if (!text) {
        return text;
    }
    return text
        .split(QUOTE)
        .join(QUOTE + QUOTE)
        .replace(/^([-+=@])/, "'$1")
        .replace(/\s+$/, '');
}
var domParser = new DOMParser();
function htmlDecoded(text) {
    if (!text) {
        return text;
    }
    var regexp = /&[^;]+;/g;
    function htmlDecoded(value) {
        var parsedDom = domParser.parseFromString(value, 'text/html');
        return parsedDom.body.textContent;
    }
    return text.replace(regexp, htmlDecoded).replace(regexp, htmlDecoded);
}
function formatSpecialHeader(useExcelHeader) {
    return useExcelHeader ? "sep=" + END_COLUMN + END_ROW : '';
}
function formatRow(row, addEndRowDelimiter) {
    if (addEndRowDelimiter === void 0) { addEndRowDelimiter = true; }
    var text = '';
    for (var i = 0; i < row.length; i += 1) {
        if (Object(lodash__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(row[i]) || Object(lodash__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(row[i]) || Object(util__WEBPACK_IMPORTED_MODULE_3__["isNullOrUndefined"])(row[i])) {
            text += row[i];
        }
        else {
            text += "" + QUOTE + csvEscaped(Object(lodash__WEBPACK_IMPORTED_MODULE_1__["unescape"])(htmlDecoded(row[i]))) + QUOTE;
        }
        if (i < row.length - 1) {
            text += END_COLUMN;
        }
    }
    return addEndRowDelimiter ? text + END_ROW : text;
}
function convertSeriesListToCsv(seriesList, options) {
    var _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaultOptions, options), dateTimeFormat = _a.dateTimeFormat, excel = _a.excel, timezone = _a.timezone;
    var text = formatSpecialHeader(excel) + formatRow(['Series', 'Time', 'Value']);
    for (var seriesIndex = 0; seriesIndex < seriesList.length; seriesIndex += 1) {
        for (var i = 0; i < seriesList[seriesIndex].datapoints.length; i += 1) {
            text += formatRow([
                seriesList[seriesIndex].alias,
                timezone === 'utc'
                    ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(seriesList[seriesIndex].datapoints[i][POINT_TIME_INDEX])
                        .utc()
                        .format(dateTimeFormat)
                    : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(seriesList[seriesIndex].datapoints[i][POINT_TIME_INDEX]).format(dateTimeFormat),
                seriesList[seriesIndex].datapoints[i][POINT_VALUE_INDEX],
            ], i < seriesList[seriesIndex].datapoints.length - 1 || seriesIndex < seriesList.length - 1);
        }
    }
    return text;
}
function exportSeriesListToCsv(seriesList, options) {
    var text = convertSeriesListToCsv(seriesList, options);
    saveSaveBlob(text, EXPORT_FILENAME);
}
function convertSeriesListToCsvColumns(seriesList, options) {
    var _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, defaultOptions, options), dateTimeFormat = _a.dateTimeFormat, excel = _a.excel, timezone = _a.timezone;
    // add header
    var text = formatSpecialHeader(excel) +
        formatRow(['Time'].concat(seriesList.map(function (val) {
            return val.alias;
        })));
    // process data
    var extendedDatapointsList = mergeSeriesByTime(seriesList);
    var _loop_1 = function (i) {
        var timestamp = timezone === 'utc'
            ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(extendedDatapointsList[0][i][POINT_TIME_INDEX])
                .utc()
                .format(dateTimeFormat)
            : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(extendedDatapointsList[0][i][POINT_TIME_INDEX]).format(dateTimeFormat);
        text += formatRow([timestamp].concat(extendedDatapointsList.map(function (datapoints) {
            return datapoints[i][POINT_VALUE_INDEX];
        })), i < extendedDatapointsList[0].length - 1);
    };
    // make text
    for (var i = 0; i < extendedDatapointsList[0].length; i += 1) {
        _loop_1(i);
    }
    return text;
}
/**
 * Collect all unique timestamps from series list and use it to fill
 * missing points by null.
 */
function mergeSeriesByTime(seriesList) {
    var timestamps = [];
    for (var i = 0; i < seriesList.length; i++) {
        var seriesPoints = seriesList[i].datapoints;
        for (var j = 0; j < seriesPoints.length; j++) {
            timestamps.push(seriesPoints[j][POINT_TIME_INDEX]);
        }
    }
    timestamps = Object(lodash__WEBPACK_IMPORTED_MODULE_1__["sortedUniq"])(timestamps.sort());
    var result = [];
    for (var i = 0; i < seriesList.length; i++) {
        var seriesPoints = seriesList[i].datapoints;
        var seriesTimestamps = seriesPoints.map(function (p) { return p[POINT_TIME_INDEX]; });
        var extendedDatapoints = [];
        for (var j = 0; j < timestamps.length; j++) {
            var timestamp = timestamps[j];
            var pointIndex = Object(lodash__WEBPACK_IMPORTED_MODULE_1__["sortedIndexOf"])(seriesTimestamps, timestamp);
            if (pointIndex !== -1) {
                extendedDatapoints.push(seriesPoints[pointIndex]);
            }
            else {
                extendedDatapoints.push([null, timestamp]);
            }
        }
        result.push(extendedDatapoints);
    }
    return result;
}
function exportSeriesListToCsvColumns(seriesList, options) {
    var text = convertSeriesListToCsvColumns(seriesList, options);
    saveSaveBlob(text, EXPORT_FILENAME);
}
function convertTableDataToCsv(table, excel) {
    if (excel === void 0) { excel = false; }
    var text = formatSpecialHeader(excel);
    // add headline
    text += formatRow(table.columns.map(function (val) { return val.title || val.text; }));
    // process data
    for (var i = 0; i < table.rows.length; i += 1) {
        text += formatRow(table.rows[i], i < table.rows.length - 1);
    }
    return text;
}
function exportTableDataToCsv(table, excel) {
    if (excel === void 0) { excel = false; }
    var text = convertTableDataToCsv(table, excel);
    saveSaveBlob(text, EXPORT_FILENAME);
}
function saveSaveBlob(payload, fname) {
    var blob = new Blob([payload], { type: 'text/csv;charset=utf-8;header=present;' });
    Object(file_saver__WEBPACK_IMPORTED_MODULE_2__["saveAs"])(blob, fname);
}


/***/ }),

/***/ "./public/app/core/utils/flatten.ts":
/*!******************************************!*\
  !*** ./public/app/core/utils/flatten.ts ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return flatten; });
// Copyright (c) 2014, Hugh Kennedy
// Based on code from https://github.com/hughsk/flat/blob/master/index.js
//
function flatten(target, opts) {
    opts = opts || {};
    var delimiter = opts.delimiter || '.';
    var maxDepth = opts.maxDepth || 3;
    var currentDepth = 1;
    var output = {};
    function step(object, prev) {
        Object.keys(object).forEach(function (key) {
            var value = object[key];
            var isarray = opts.safe && Array.isArray(value);
            var type = Object.prototype.toString.call(value);
            var isobject = type === '[object Object]';
            var newKey = prev ? prev + delimiter + key : key;
            if (!opts.maxDepth) {
                maxDepth = currentDepth + 1;
            }
            if (!isarray && isobject && Object.keys(value).length && currentDepth < maxDepth) {
                ++currentDepth;
                return step(value, newKey);
            }
            output[newKey] = value;
        });
    }
    step(target, null);
    return output;
}


/***/ }),

/***/ "./public/app/core/utils/kbn.ts":
/*!**************************************!*\
  !*** ./public/app/core/utils/kbn.ts ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");



var kbn = {};
kbn.valueFormats = {};
kbn.regexEscape = function (value) {
    return value.replace(/[\\^$*+?.()|[\]{}\/]/g, '\\$&');
};
///// HELPER FUNCTIONS /////
kbn.round_interval = function (interval) {
    switch (true) {
        // 0.015s
        case interval < 15:
            return 10; // 0.01s
        // 0.035s
        case interval < 35:
            return 20; // 0.02s
        // 0.075s
        case interval < 75:
            return 50; // 0.05s
        // 0.15s
        case interval < 150:
            return 100; // 0.1s
        // 0.35s
        case interval < 350:
            return 200; // 0.2s
        // 0.75s
        case interval < 750:
            return 500; // 0.5s
        // 1.5s
        case interval < 1500:
            return 1000; // 1s
        // 3.5s
        case interval < 3500:
            return 2000; // 2s
        // 7.5s
        case interval < 7500:
            return 5000; // 5s
        // 12.5s
        case interval < 12500:
            return 10000; // 10s
        // 17.5s
        case interval < 17500:
            return 15000; // 15s
        // 25s
        case interval < 25000:
            return 20000; // 20s
        // 45s
        case interval < 45000:
            return 30000; // 30s
        // 1.5m
        case interval < 90000:
            return 60000; // 1m
        // 3.5m
        case interval < 210000:
            return 120000; // 2m
        // 7.5m
        case interval < 450000:
            return 300000; // 5m
        // 12.5m
        case interval < 750000:
            return 600000; // 10m
        // 12.5m
        case interval < 1050000:
            return 900000; // 15m
        // 25m
        case interval < 1500000:
            return 1200000; // 20m
        // 45m
        case interval < 2700000:
            return 1800000; // 30m
        // 1.5h
        case interval < 5400000:
            return 3600000; // 1h
        // 2.5h
        case interval < 9000000:
            return 7200000; // 2h
        // 4.5h
        case interval < 16200000:
            return 10800000; // 3h
        // 9h
        case interval < 32400000:
            return 21600000; // 6h
        // 1d
        case interval < 86400000:
            return 43200000; // 12h
        // 1w
        case interval < 604800000:
            return 86400000; // 1d
        // 3w
        case interval < 1814400000:
            return 604800000; // 1w
        // 6w
        case interval < 3628800000:
            return 2592000000; // 30d
        default:
            return 31536000000; // 1y
    }
};
kbn.secondsToHms = function (seconds) {
    var numyears = Math.floor(seconds / 31536000);
    if (numyears) {
        return numyears + 'y';
    }
    var numdays = Math.floor((seconds % 31536000) / 86400);
    if (numdays) {
        return numdays + 'd';
    }
    var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
    if (numhours) {
        return numhours + 'h';
    }
    var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
    if (numminutes) {
        return numminutes + 'm';
    }
    var numseconds = Math.floor((((seconds % 31536000) % 86400) % 3600) % 60);
    if (numseconds) {
        return numseconds + 's';
    }
    var nummilliseconds = Math.floor(seconds * 1000.0);
    if (nummilliseconds) {
        return nummilliseconds + 'ms';
    }
    return 'less than a millisecond'; //'just now' //or other string you like;
};
kbn.secondsToHhmmss = function (seconds) {
    var strings = [];
    var numhours = Math.floor(seconds / 3600);
    var numminutes = Math.floor((seconds % 3600) / 60);
    var numseconds = Math.floor((seconds % 3600) % 60);
    numhours > 9 ? strings.push('' + numhours) : strings.push('0' + numhours);
    numminutes > 9 ? strings.push('' + numminutes) : strings.push('0' + numminutes);
    numseconds > 9 ? strings.push('' + numseconds) : strings.push('0' + numseconds);
    return strings.join(':');
};
kbn.to_percent = function (nr, outof) {
    return Math.floor((nr / outof) * 10000) / 100 + '%';
};
kbn.addslashes = function (str) {
    str = str.replace(/\\/g, '\\\\');
    str = str.replace(/\'/g, "\\'");
    str = str.replace(/\"/g, '\\"');
    str = str.replace(/\0/g, '\\0');
    return str;
};
kbn.interval_regex = /(\d+(?:\.\d+)?)(ms|[Mwdhmsy])/;
// histogram & trends
kbn.intervals_in_seconds = {
    y: 31536000,
    M: 2592000,
    w: 604800,
    d: 86400,
    h: 3600,
    m: 60,
    s: 1,
    ms: 0.001,
};
kbn.calculateInterval = function (range, resolution, lowLimitInterval) {
    var lowLimitMs = 1; // 1 millisecond default low limit
    var intervalMs;
    if (lowLimitInterval) {
        if (lowLimitInterval[0] === '>') {
            lowLimitInterval = lowLimitInterval.slice(1);
        }
        lowLimitMs = kbn.interval_to_ms(lowLimitInterval);
    }
    intervalMs = kbn.round_interval((range.to.valueOf() - range.from.valueOf()) / resolution);
    if (lowLimitMs > intervalMs) {
        intervalMs = lowLimitMs;
    }
    return {
        intervalMs: intervalMs,
        interval: kbn.secondsToHms(intervalMs / 1000),
    };
};
kbn.describe_interval = function (str) {
    var matches = str.match(kbn.interval_regex);
    if (!matches || !Object(lodash__WEBPACK_IMPORTED_MODULE_0__["has"])(kbn.intervals_in_seconds, matches[2])) {
        throw new Error('Invalid interval string, expecting a number followed by one of "Mwdhmsy"');
    }
    else {
        return {
            sec: kbn.intervals_in_seconds[matches[2]],
            type: matches[2],
            count: parseInt(matches[1], 10),
        };
    }
};
kbn.interval_to_ms = function (str) {
    var info = kbn.describe_interval(str);
    return info.sec * 1000 * info.count;
};
kbn.interval_to_seconds = function (str) {
    var info = kbn.describe_interval(str);
    return info.sec * info.count;
};
kbn.query_color_dot = function (color, diameter) {
    return ('<div class="icon-circle" style="' +
        ['display:inline-block', 'color:' + color, 'font-size:' + diameter + 'px'].join(';') +
        '"></div>');
};
kbn.slugifyForUrl = function (str) {
    return str
        .toLowerCase()
        .replace(/[^\w ]+/g, '')
        .replace(/ +/g, '-');
};
/** deprecated since 6.1, use grafana/data */
kbn.stringToJsRegex = function (str) {
    Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["deprecationWarning"])('kbn.ts', 'kbn.stringToJsRegex()', '@grafana/data');
    return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["stringToJsRegex"])(str);
};
kbn.toFixed = function (value, decimals) {
    if (value === null) {
        return '';
    }
    var factor = decimals ? Math.pow(10, Math.max(0, decimals)) : 1;
    var formatted = String(Math.round(value * factor) / factor);
    // if exponent return directly
    if (formatted.indexOf('e') !== -1 || value === 0) {
        return formatted;
    }
    // If tickDecimals was specified, ensure that we have exactly that
    // much precision; otherwise default to the value's own precision.
    if (decimals != null) {
        var decimalPos = formatted.indexOf('.');
        var precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1;
        if (precision < decimals) {
            return (precision ? formatted : formatted + '.') + String(factor).substr(1, decimals - precision);
        }
    }
    return formatted;
};
kbn.toFixedScaled = function (value, decimals, scaledDecimals, additionalDecimals, ext) {
    if (scaledDecimals === null) {
        return kbn.toFixed(value, decimals) + ext;
    }
    else {
        return kbn.toFixed(value, scaledDecimals + additionalDecimals) + ext;
    }
};
kbn.roundValue = function (num, decimals) {
    if (num === null) {
        return null;
    }
    var n = Math.pow(10, decimals);
    var formatted = (n * num).toFixed(decimals);
    return Math.round(parseFloat(formatted)) / n;
};
///// FORMAT MENU /////
kbn.getUnitFormats = function () {
    return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getValueFormats"])();
};
//
// Backward compatible layer for value formats to support old plugins
//
if (typeof Proxy !== 'undefined') {
    kbn.valueFormats = new Proxy(kbn.valueFormats, {
        get: function (target, name, receiver) {
            if (typeof name !== 'string') {
                throw { message: "Value format " + String(name) + " is not a string" };
            }
            var formatter = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getValueFormat"])(name);
            if (formatter) {
                return formatter;
            }
            // default to look here
            return Reflect.get(target, name, receiver);
        },
    });
}
else {
    kbn.valueFormats = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getValueFormatterIndex"])();
}
/* harmony default export */ __webpack_exports__["default"] = (kbn);


/***/ }),

/***/ "./public/app/core/utils/location_util.ts":
/*!************************************************!*\
  !*** ./public/app/core/utils/location_util.ts ***!
  \************************************************/
/*! exports provided: stripBaseFromUrl, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripBaseFromUrl", function() { return stripBaseFromUrl; });
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");

var stripBaseFromUrl = function (url) {
    var appSubUrl = app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].appSubUrl;
    var stripExtraChars = appSubUrl.endsWith('/') ? 1 : 0;
    var urlWithoutBase = url.length > 0 && url.indexOf(appSubUrl) === 0 ? url.slice(appSubUrl.length - stripExtraChars) : url;
    return urlWithoutBase;
};
/* harmony default export */ __webpack_exports__["default"] = ({ stripBaseFromUrl: stripBaseFromUrl });


/***/ }),

/***/ "./public/app/core/utils/model_utils.ts":
/*!**********************************************!*\
  !*** ./public/app/core/utils/model_utils.ts ***!
  \**********************************************/
/*! exports provided: assignModelProperties */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignModelProperties", function() { return assignModelProperties; });
function assignModelProperties(target, source, defaults, removeDefaults) {
    for (var key in defaults) {
        if (!defaults.hasOwnProperty(key)) {
            continue;
        }
        target[key] = source[key] === undefined ? defaults[key] : source[key];
    }
}


/***/ }),

/***/ "./public/app/core/utils/outline.ts":
/*!******************************************!*\
  !*** ./public/app/core/utils/outline.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

// based on http://www.paciellogroup.com/blog/2012/04/how-to-remove-css-outlines-in-an-accessible-manner/
function outlineFixer() {
    var d = document;
    var styleElement = d.createElement('STYLE');
    var domEvents = 'addEventListener' in d;
    var addEventListener = function (type, callback) {
        // Basic cross-browser event handling
        if (domEvents) {
            d.addEventListener(type, callback);
        }
        else {
            d.attachEvent('on' + type, callback);
        }
    };
    var setCss = function (cssText) {
        // Handle setting of <style> element contents in IE8
        !!styleElement.styleSheet ? (styleElement.styleSheet.cssText = cssText) : (styleElement.innerHTML = cssText);
    };
    d.getElementsByTagName('HEAD')[0].appendChild(styleElement);
    // Using mousedown instead of mouseover, so that previously focused elements don't lose focus ring on mouse move
    addEventListener('mousedown', function () {
        setCss(':focus{outline:0 !important}::-moz-focus-inner{border:0;}');
    });
    addEventListener('keydown', function () {
        setCss('');
    });
}
outlineFixer();


/***/ }),

/***/ "./public/app/core/utils/query.ts":
/*!****************************************!*\
  !*** ./public/app/core/utils/query.ts ***!
  \****************************************/
/*! exports provided: getNextRefIdChar */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextRefIdChar", function() { return getNextRefIdChar; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

var getNextRefIdChar = function (queries) {
    var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(letters, function (refId) {
        return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.every(queries, function (other) {
            return other.refId !== refId;
        });
    });
};


/***/ }),

/***/ "./public/app/core/utils/react2angular.ts":
/*!************************************************!*\
  !*** ./public/app/core/utils/react2angular.ts ***!
  \************************************************/
/*! exports provided: react2AngularDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "react2AngularDirective", function() { return react2AngularDirective; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/ConfigProvider */ "./public/app/core/utils/ConfigProvider.tsx");


function react2AngularDirective(name, component, options) {
    app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive(name, [
        'reactDirective',
        function (reactDirective) {
            return reactDirective(Object(app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_1__["provideTheme"])(component), options);
        },
    ]);
}


/***/ }),

/***/ "./public/app/core/utils/scrollbar.ts":
/*!********************************************!*\
  !*** ./public/app/core/utils/scrollbar.ts ***!
  \********************************************/
/*! exports provided: default, addClassIfNoOverlayScrollbar */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getScrollbarWidth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addClassIfNoOverlayScrollbar", function() { return addClassIfNoOverlayScrollbar; });
// Slightly modified, but without dependancies:
// https://raw.githubusercontent.com/malte-wessel/react-custom-scrollbars/master/src/utils/getScrollbarWidth.js
var scrollbarWidth = null;
function getScrollbarWidth() {
    if (scrollbarWidth !== null) {
        return scrollbarWidth;
    }
    if (typeof document !== 'undefined') {
        var div_1 = document.createElement('div');
        var newStyles_1 = {
            width: '100px',
            height: '100px',
            position: 'absolute',
            top: '-9999px',
            overflow: 'scroll',
            MsOverflowStyle: 'scrollbar',
        };
        Object.keys(newStyles_1).map(function (style) {
            // @ts-ignore
            div_1.style[style] = newStyles_1[style];
        });
        document.body.appendChild(div_1);
        scrollbarWidth = div_1.offsetWidth - div_1.clientWidth;
        document.body.removeChild(div_1);
    }
    else {
        scrollbarWidth = 0;
    }
    return scrollbarWidth || 0;
}
var hasNoOverlayScrollbars = getScrollbarWidth() > 0;
var addClassIfNoOverlayScrollbar = function (classname, htmlElement) {
    if (htmlElement === void 0) { htmlElement = document.body; }
    if (hasNoOverlayScrollbars) {
        htmlElement.classList.add(classname);
    }
};


/***/ }),

/***/ "./public/app/core/utils/sort_by_keys.ts":
/*!***********************************************!*\
  !*** ./public/app/core/utils/sort_by_keys.ts ***!
  \***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return sortByKeys; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


function sortByKeys(input) {
    var e_1, _a;
    if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(input)) {
        return input.map(sortByKeys);
    }
    if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isPlainObject(input)) {
        var sortedObject = {};
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](lodash__WEBPACK_IMPORTED_MODULE_1___default.a.keys(input).sort()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var key = _c.value;
                sortedObject[key] = sortByKeys(input[key]);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return sortedObject;
    }
    return input;
}


/***/ }),

/***/ "./public/app/core/utils/tags.ts":
/*!***************************************!*\
  !*** ./public/app/core/utils/tags.ts ***!
  \***************************************/
/*! exports provided: getTagColorsFromName, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTagColorsFromName", function() { return getTagColorsFromName; });
var TAG_COLORS = [
    '#E24D42',
    '#1F78C1',
    '#BA43A9',
    '#705DA0',
    '#466803',
    '#508642',
    '#447EBC',
    '#C15C17',
    '#890F02',
    '#757575',
    '#0A437C',
    '#6D1F62',
    '#584477',
    '#629E51',
    '#2F4F4F',
    '#BF1B00',
    '#806EB7',
    '#8a2eb8',
    '#699e00',
    '#000000',
    '#3F6833',
    '#2F575E',
    '#99440A',
    '#E0752D',
    '#0E4AB4',
    '#58140C',
    '#052B51',
    '#511749',
    '#3F2B5B',
];
var TAG_BORDER_COLORS = [
    '#FF7368',
    '#459EE7',
    '#E069CF',
    '#9683C6',
    '#6C8E29',
    '#76AC68',
    '#6AA4E2',
    '#E7823D',
    '#AF3528',
    '#9B9B9B',
    '#3069A2',
    '#934588',
    '#7E6A9D',
    '#88C477',
    '#557575',
    '#E54126',
    '#A694DD',
    '#B054DE',
    '#8FC426',
    '#262626',
    '#658E59',
    '#557D84',
    '#BF6A30',
    '#FF9B53',
    '#3470DA',
    '#7E3A32',
    '#2B5177',
    '#773D6F',
    '#655181',
];
/**
 * Returns tag badge background and border colors based on hashed tag name.
 * @param name tag name
 */
function getTagColorsFromName(name) {
    var hash = djb2(name.toLowerCase());
    var color = TAG_COLORS[Math.abs(hash % TAG_COLORS.length)];
    var borderColor = TAG_BORDER_COLORS[Math.abs(hash % TAG_BORDER_COLORS.length)];
    return { color: color, borderColor: borderColor };
}
function djb2(str) {
    var hash = 5381;
    for (var i = 0; i < str.length; i++) {
        hash = (hash << 5) + hash + str.charCodeAt(i); /* hash * 33 + c */
    }
    return hash;
}
/* harmony default export */ __webpack_exports__["default"] = ({
    getTagColorsFromName: getTagColorsFromName,
});


/***/ }),

/***/ "./public/app/core/utils/text.ts":
/*!***************************************!*\
  !*** ./public/app/core/utils/text.ts ***!
  \***************************************/
/*! exports provided: sanitize, hasAnsiCodes, escapeHtml */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sanitize", function() { return sanitize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasAnsiCodes", function() { return hasAnsiCodes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "escapeHtml", function() { return escapeHtml; });
/* harmony import */ var xss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! xss */ "./node_modules/xss/lib/index.js");
/* harmony import */ var xss__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(xss__WEBPACK_IMPORTED_MODULE_0__);

var XSSWL = Object.keys(xss__WEBPACK_IMPORTED_MODULE_0___default.a.whiteList).reduce(function (acc, element) {
    // @ts-ignore
    acc[element] = xss__WEBPACK_IMPORTED_MODULE_0___default.a.whiteList[element].concat(['class', 'style']);
    return acc;
}, {});
var sanitizeXSS = new xss__WEBPACK_IMPORTED_MODULE_0___default.a.FilterXSS({
    whiteList: XSSWL,
});
/**
 * Returns string safe from XSS attacks.
 *
 * Even though we allow the style-attribute, there's still default filtering applied to it
 * Info: https://github.com/leizongmin/js-xss#customize-css-filter
 * Whitelist: https://github.com/leizongmin/js-css-filter/blob/master/lib/default.js
 */
function sanitize(unsanitizedString) {
    try {
        return sanitizeXSS.process(unsanitizedString);
    }
    catch (error) {
        console.log('String could not be sanitized', unsanitizedString);
        return unsanitizedString;
    }
}
function hasAnsiCodes(input) {
    return /\u001b\[\d{1,2}m/.test(input);
}
function escapeHtml(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}


/***/ }),

/***/ "./public/app/core/utils/ticks.ts":
/*!****************************************!*\
  !*** ./public/app/core/utils/ticks.ts ***!
  \****************************************/
/*! exports provided: tickStep, getScaledDecimals, getFlotTickSize, getFlotRange, getFlotTickDecimals, grafanaTimeFormat, logp, getPrecision, getStringPrecision */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tickStep", function() { return tickStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getScaledDecimals", function() { return getScaledDecimals; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFlotTickSize", function() { return getFlotTickSize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFlotRange", function() { return getFlotRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFlotTickDecimals", function() { return getFlotTickDecimals; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grafanaTimeFormat", function() { return grafanaTimeFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logp", function() { return logp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPrecision", function() { return getPrecision; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStringPrecision", function() { return getStringPrecision; });
/**
 * Calculate tick step.
 * Implementation from d3-array (ticks.js)
 * https://github.com/d3/d3-array/blob/master/src/ticks.js
 * @param start Start value
 * @param stop End value
 * @param count Ticks count
 */
function tickStep(start, stop, count) {
    var e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2);
    var step0 = Math.abs(stop - start) / Math.max(0, count);
    var step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10));
    var error = step0 / step1;
    if (error >= e10) {
        step1 *= 10;
    }
    else if (error >= e5) {
        step1 *= 5;
    }
    else if (error >= e2) {
        step1 *= 2;
    }
    return stop < start ? -step1 : step1;
}
function getScaledDecimals(decimals, tickSize) {
    return decimals - Math.floor(Math.log(tickSize) / Math.LN10);
}
/**
 * Calculate tick size based on min and max values, number of ticks and precision.
 * Implementation from Flot.
 * @param min           Axis minimum
 * @param max           Axis maximum
 * @param noTicks       Number of ticks
 * @param tickDecimals  Tick decimal precision
 */
function getFlotTickSize(min, max, noTicks, tickDecimals) {
    var delta = (max - min) / noTicks;
    var dec = -Math.floor(Math.log(delta) / Math.LN10);
    var maxDec = tickDecimals;
    var magn = Math.pow(10, -dec);
    var norm = delta / magn; // norm is between 1.0 and 10.0
    var size;
    if (norm < 1.5) {
        size = 1;
    }
    else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
            size = 2.5;
            ++dec;
        }
    }
    else if (norm < 7.5) {
        size = 5;
    }
    else {
        size = 10;
    }
    size *= magn;
    return size;
}
/**
 * Calculate axis range (min and max).
 * Implementation from Flot.
 */
function getFlotRange(panelMin, panelMax, datamin, datamax) {
    var autoscaleMargin = 0.02;
    var min = +(panelMin != null ? panelMin : datamin);
    var max = +(panelMax != null ? panelMax : datamax);
    var delta = max - min;
    if (delta === 0.0) {
        // Grafana fix: wide Y min and max using increased wideFactor
        // when all series values are the same
        var wideFactor = 0.25;
        var widen = Math.abs(max === 0 ? 1 : max * wideFactor);
        if (panelMin === null) {
            min -= widen;
        }
        // always widen max if we couldn't widen min to ensure we
        // don't fall into min == max which doesn't work
        if (panelMax == null || panelMin != null) {
            max += widen;
        }
    }
    else {
        // consider autoscaling
        var margin = autoscaleMargin;
        if (margin != null) {
            if (panelMin == null) {
                min -= delta * margin;
                // make sure we don't go below zero if all values
                // are positive
                if (min < 0 && datamin != null && datamin >= 0) {
                    min = 0;
                }
            }
            if (panelMax == null) {
                max += delta * margin;
                if (max > 0 && datamax != null && datamax <= 0) {
                    max = 0;
                }
            }
        }
    }
    return { min: min, max: max };
}
/**
 * Calculate tick decimals.
 * Implementation from Flot.
 */
function getFlotTickDecimals(datamin, datamax, axis, height) {
    var _a = getFlotRange(axis.min, axis.max, datamin, datamax), min = _a.min, max = _a.max;
    var noTicks = 0.3 * Math.sqrt(height);
    var delta = (max - min) / noTicks;
    var dec = -Math.floor(Math.log(delta) / Math.LN10);
    var magn = Math.pow(10, -dec);
    // norm is between 1.0 and 10.0
    var norm = delta / magn;
    var size;
    if (norm < 1.5) {
        size = 1;
    }
    else if (norm < 3) {
        size = 2;
        // special case for 2.5, requires an extra decimal
        if (norm > 2.25) {
            size = 2.5;
        }
    }
    else if (norm < 7.5) {
        size = 5;
    }
    else {
        size = 10;
    }
    size *= magn;
    var tickDecimals = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1);
    // grafana addition
    var scaledDecimals = tickDecimals - Math.floor(Math.log(size) / Math.LN10);
    return { tickDecimals: tickDecimals, scaledDecimals: scaledDecimals };
}
/**
 * Format timestamp similar to Grafana graph panel.
 * @param ticks Number of ticks
 * @param min Time from (in milliseconds)
 * @param max Time to (in milliseconds)
 */
function grafanaTimeFormat(ticks, min, max) {
    if (min && max && ticks) {
        var range = max - min;
        var secPerTick = range / ticks / 1000;
        var oneDay = 86400000;
        var oneYear = 31536000000;
        if (secPerTick <= 45) {
            return '%H:%M:%S';
        }
        if (secPerTick <= 7200 || range <= oneDay) {
            return '%H:%M';
        }
        if (secPerTick <= 80000) {
            return '%m/%d %H:%M';
        }
        if (secPerTick <= 2419200 || range <= oneYear) {
            return '%m/%d';
        }
        return '%Y-%m';
    }
    return '%H:%M';
}
/**
 * Logarithm of value for arbitrary base.
 */
function logp(value, base) {
    return Math.log(value) / Math.log(base);
}
/**
 * Get decimal precision of number (3.14 => 2)
 */
function getPrecision(num) {
    var str = num.toString();
    return getStringPrecision(str);
}
/**
 * Get decimal precision of number stored as a string ("3.14" => 2)
 */
function getStringPrecision(num) {
    if (isNaN(num)) {
        return 0;
    }
    var dotIndex = num.indexOf('.');
    if (dotIndex === -1) {
        return 0;
    }
    else {
        return num.length - dotIndex - 1;
    }
}


/***/ }),

/***/ "./public/app/core/utils/timePicker.ts":
/*!*********************************************!*\
  !*** ./public/app/core/utils/timePicker.ts ***!
  \*********************************************/
/*! exports provided: getShiftedTimeRange, getZoomedTimeRange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getShiftedTimeRange", function() { return getShiftedTimeRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getZoomedTimeRange", function() { return getZoomedTimeRange; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

var getShiftedTimeRange = function (direction, origRange) {
    var range = {
        from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(origRange.from),
        to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["toUtc"])(origRange.to),
    };
    var timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
    var to, from;
    if (direction === -1) {
        to = range.to.valueOf() - timespan;
        from = range.from.valueOf() - timespan;
    }
    else if (direction === 1) {
        to = range.to.valueOf() + timespan;
        from = range.from.valueOf() + timespan;
        if (to > Date.now() && range.to.valueOf() < Date.now()) {
            to = Date.now();
            from = range.from.valueOf();
        }
    }
    else {
        to = range.to.valueOf();
        from = range.from.valueOf();
    }
    return { from: from, to: to };
};
var getZoomedTimeRange = function (range, factor) {
    var timespan = range.to.valueOf() - range.from.valueOf();
    var center = range.to.valueOf() - timespan / 2;
    var to = center + (timespan * factor) / 2;
    var from = center - (timespan * factor) / 2;
    return { from: from, to: to };
};


/***/ }),

/***/ "./public/app/core/utils/url.ts":
/*!**************************************!*\
  !*** ./public/app/core/utils/url.ts ***!
  \**************************************/
/*! exports provided: renderUrl, encodeURIComponentAsAngularJS, toUrlParams, appendQueryToUrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderUrl", function() { return renderUrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "encodeURIComponentAsAngularJS", function() { return encodeURIComponentAsAngularJS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toUrlParams", function() { return toUrlParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendQueryToUrl", function() { return appendQueryToUrl; });
/**
 * @preserve jquery-param (c) 2015 KNOWLEDGECODE | MIT
 */
function renderUrl(path, query) {
    if (query && Object.keys(query).length > 0) {
        path += '?' + toUrlParams(query);
    }
    return path;
}
function encodeURIComponentAsAngularJS(val, pctEncodeSpaces) {
    return encodeURIComponent(val)
        .replace(/%40/gi, '@')
        .replace(/%3A/gi, ':')
        .replace(/%24/g, '$')
        .replace(/%2C/gi, ',')
        .replace(/%3B/gi, ';')
        .replace(/%20/g, pctEncodeSpaces ? '%20' : '+');
}
function toUrlParams(a) {
    var s = [];
    var rbracket = /\[\]$/;
    var isArray = function (obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
    };
    var add = function (k, v) {
        v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
        if (typeof v !== 'boolean') {
            s[s.length] = encodeURIComponentAsAngularJS(k, true) + '=' + encodeURIComponentAsAngularJS(v, true);
        }
        else {
            s[s.length] = encodeURIComponentAsAngularJS(k, true);
        }
    };
    var buildParams = function (prefix, obj) {
        var i, len, key;
        if (prefix) {
            if (isArray(obj)) {
                for (i = 0, len = obj.length; i < len; i++) {
                    if (rbracket.test(prefix)) {
                        add(prefix, obj[i]);
                    }
                    else {
                        buildParams(prefix, obj[i]);
                    }
                }
            }
            else if (obj && String(obj) === '[object Object]') {
                for (key in obj) {
                    buildParams(prefix + '[' + key + ']', obj[key]);
                }
            }
            else {
                add(prefix, obj);
            }
        }
        else if (isArray(obj)) {
            for (i = 0, len = obj.length; i < len; i++) {
                add(obj[i].name, obj[i].value);
            }
        }
        else {
            for (key in obj) {
                buildParams(key, obj[key]);
            }
        }
        return s;
    };
    return buildParams('', a).join('&');
}
function appendQueryToUrl(url, stringToAppend) {
    if (stringToAppend !== undefined && stringToAppend !== null && stringToAppend !== '') {
        var pos = url.indexOf('?');
        if (pos !== -1) {
            if (url.length - pos > 1) {
                url += '&';
            }
        }
        else {
            url += '?';
        }
        url += stringToAppend;
    }
    return url;
}


/***/ }),

/***/ "./public/app/features/admin/AdminEditOrgCtrl.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/admin/AdminEditOrgCtrl.ts ***!
  \*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var AdminEditOrgCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdminEditOrgCtrl($scope, $routeParams, backendSrv, $location, navModelSrv) {
        $scope.init = function () {
            $scope.navModel = navModelSrv.getNav('admin', 'global-orgs', 0);
            if ($routeParams.id) {
                $scope.getOrg($routeParams.id);
                $scope.getOrgUsers($routeParams.id);
            }
        };
        $scope.getOrg = function (id) {
            backendSrv.get('/api/orgs/' + id).then(function (org) {
                $scope.org = org;
            });
        };
        $scope.getOrgUsers = function (id) {
            backendSrv.get('/api/orgs/' + id + '/users').then(function (orgUsers) {
                $scope.orgUsers = orgUsers;
            });
        };
        $scope.update = function () {
            if (!$scope.orgDetailsForm.$valid) {
                return;
            }
            backendSrv.put('/api/orgs/' + $scope.org.id, $scope.org).then(function () {
                $location.path('/admin/orgs');
            });
        };
        $scope.updateOrgUser = function (orgUser) {
            backendSrv.patch('/api/orgs/' + orgUser.orgId + '/users/' + orgUser.userId, orgUser);
        };
        $scope.removeOrgUser = function (orgUser) {
            backendSrv.delete('/api/orgs/' + orgUser.orgId + '/users/' + orgUser.userId).then(function () {
                $scope.getOrgUsers($scope.org.id);
            });
        };
        $scope.init();
    }
    return AdminEditOrgCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (AdminEditOrgCtrl);


/***/ }),

/***/ "./public/app/features/admin/AdminEditUserCtrl.ts":
/*!********************************************************!*\
  !*** ./public/app/features/admin/AdminEditUserCtrl.ts ***!
  \********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");


var AdminEditUserCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdminEditUserCtrl($scope, $routeParams, backendSrv, $location, navModelSrv) {
        $scope.user = {};
        $scope.sessions = [];
        $scope.newOrg = { name: '', role: 'Editor' };
        $scope.permissions = {};
        $scope.navModel = navModelSrv.getNav('admin', 'global-users', 0);
        $scope.init = function () {
            if ($routeParams.id) {
                $scope.getUser($routeParams.id);
                $scope.getUserSessions($routeParams.id);
                $scope.getUserOrgs($routeParams.id);
            }
        };
        $scope.getUser = function (id) {
            backendSrv.get('/api/users/' + id).then(function (user) {
                $scope.user = user;
                $scope.user_id = id;
                $scope.permissions.isGrafanaAdmin = user.isGrafanaAdmin;
            });
        };
        $scope.getUserSessions = function (id) {
            backendSrv.get('/api/admin/users/' + id + '/auth-tokens').then(function (sessions) {
                sessions.reverse();
                $scope.sessions = sessions.map(function (session) {
                    return {
                        id: session.id,
                        isActive: session.isActive,
                        seenAt: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["dateTime"])(session.seenAt).fromNow(),
                        createdAt: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["dateTime"])(session.createdAt).format('MMMM DD, YYYY'),
                        clientIp: session.clientIp,
                        browser: session.browser,
                        browserVersion: session.browserVersion,
                        os: session.os,
                        osVersion: session.osVersion,
                        device: session.device,
                    };
                });
            });
        };
        $scope.revokeUserSession = function (tokenId) {
            backendSrv
                .post('/api/admin/users/' + $scope.user_id + '/revoke-auth-token', {
                authTokenId: tokenId,
            })
                .then(function () {
                $scope.sessions = $scope.sessions.filter(function (session) {
                    if (session.id === tokenId) {
                        return false;
                    }
                    return true;
                });
            });
        };
        $scope.revokeAllUserSessions = function (tokenId) {
            backendSrv.post('/api/admin/users/' + $scope.user_id + '/logout').then(function () {
                $scope.sessions = [];
            });
        };
        $scope.setPassword = function () {
            if (!$scope.passwordForm.$valid) {
                return;
            }
            var payload = { password: $scope.password };
            backendSrv.put('/api/admin/users/' + $scope.user_id + '/password', payload).then(function () {
                $location.path('/admin/users');
            });
        };
        $scope.updatePermissions = function () {
            var payload = $scope.permissions;
            backendSrv.put('/api/admin/users/' + $scope.user_id + '/permissions', payload);
        };
        $scope.create = function () {
            if (!$scope.userForm.$valid) {
                return;
            }
            backendSrv.post('/api/admin/users', $scope.user).then(function () {
                $location.path('/admin/users');
            });
        };
        $scope.getUserOrgs = function (id) {
            backendSrv.get('/api/users/' + id + '/orgs').then(function (orgs) {
                $scope.orgs = orgs;
            });
        };
        $scope.update = function () {
            if (!$scope.userForm.$valid) {
                return;
            }
            backendSrv.put('/api/users/' + $scope.user_id, $scope.user).then(function () {
                $location.path('/admin/users');
            });
        };
        $scope.updateOrgUser = function (orgUser) {
            backendSrv.patch('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id, orgUser).then(function () { });
        };
        $scope.removeOrgUser = function (orgUser) {
            backendSrv.delete('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id).then(function () {
                $scope.getUser($scope.user_id);
                $scope.getUserOrgs($scope.user_id);
            });
        };
        $scope.orgsSearchCache = [];
        $scope.searchOrgs = function (queryStr, callback) {
            if ($scope.orgsSearchCache.length > 0) {
                callback(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map($scope.orgsSearchCache, 'name'));
                return;
            }
            backendSrv.get('/api/orgs', { query: '' }).then(function (result) {
                $scope.orgsSearchCache = result;
                callback(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(result, 'name'));
            });
        };
        $scope.addOrgUser = function () {
            if (!$scope.addOrgForm.$valid) {
                return;
            }
            var orgInfo = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find($scope.orgsSearchCache, {
                name: $scope.newOrg.name,
            });
            if (!orgInfo) {
                return;
            }
            $scope.newOrg.loginOrEmail = $scope.user.login;
            backendSrv.post('/api/orgs/' + orgInfo.id + '/users/', $scope.newOrg).then(function () {
                $scope.getUser($scope.user_id);
                $scope.getUserOrgs($scope.user_id);
            });
        };
        $scope.deleteUser = function (user) {
            $scope.appEvent('confirm-modal', {
                title: 'Delete',
                text: 'Do you want to delete ' + user.login + '?',
                icon: 'fa-trash',
                yesText: 'Delete',
                onConfirm: function () {
                    backendSrv.delete('/api/admin/users/' + user.id).then(function () {
                        $location.path('/admin/users');
                    });
                },
            });
        };
        $scope.disableUser = function (event) {
            var user = $scope.user;
            // External user can not be disabled
            if (user.isExternal) {
                event.preventDefault();
                event.stopPropagation();
                return;
            }
            var actionEndpoint = user.isDisabled ? '/enable' : '/disable';
            backendSrv.post('/api/admin/users/' + user.id + actionEndpoint).then(function () {
                $scope.init();
            });
        };
        $scope.init();
    }
    return AdminEditUserCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (AdminEditUserCtrl);


/***/ }),

/***/ "./public/app/features/admin/AdminListOrgsCtrl.ts":
/*!********************************************************!*\
  !*** ./public/app/features/admin/AdminListOrgsCtrl.ts ***!
  \********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var AdminListOrgsCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdminListOrgsCtrl($scope, backendSrv, navModelSrv) {
        $scope.init = function () {
            $scope.navModel = navModelSrv.getNav('admin', 'global-orgs', 0);
            $scope.getOrgs();
        };
        $scope.getOrgs = function () {
            backendSrv.get('/api/orgs').then(function (orgs) {
                $scope.orgs = orgs;
            });
        };
        $scope.deleteOrg = function (org) {
            $scope.appEvent('confirm-modal', {
                title: 'Delete',
                text: 'Do you want to delete organization ' + org.name + '?',
                text2: 'All dashboards for this organization will be removed!',
                icon: 'fa-trash',
                yesText: 'Delete',
                onConfirm: function () {
                    backendSrv.delete('/api/orgs/' + org.id).then(function () {
                        $scope.getOrgs();
                    });
                },
            });
        };
        $scope.init();
    }
    return AdminListOrgsCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (AdminListOrgsCtrl);


/***/ }),

/***/ "./public/app/features/admin/AdminListUsersCtrl.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/admin/AdminListUsersCtrl.ts ***!
  \*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_utils_tags__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/tags */ "./public/app/core/utils/tags.ts");


var AdminListUsersCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdminListUsersCtrl(backendSrv, navModelSrv) {
        this.backendSrv = backendSrv;
        this.pages = [];
        this.perPage = 50;
        this.page = 1;
        this.showPaging = false;
        this.navModel = navModelSrv.getNav('admin', 'global-users', 0);
        this.query = '';
        this.getUsers();
    }
    AdminListUsersCtrl.prototype.getUsers = function () {
        var _this = this;
        this.backendSrv
            .get("/api/users/search?perpage=" + this.perPage + "&page=" + this.page + "&query=" + this.query)
            .then(function (result) {
            _this.users = result.users;
            _this.page = result.page;
            _this.perPage = result.perPage;
            _this.totalPages = Math.ceil(result.totalCount / result.perPage);
            _this.showPaging = _this.totalPages > 1;
            _this.pages = [];
            for (var i = 1; i < _this.totalPages + 1; i++) {
                _this.pages.push({ page: i, current: i === _this.page });
            }
            _this.addUsersAuthLabels();
        });
    };
    AdminListUsersCtrl.prototype.navigateToPage = function (page) {
        this.page = page.page;
        this.getUsers();
    };
    AdminListUsersCtrl.prototype.addUsersAuthLabels = function () {
        var e_1, _a;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.users), _c = _b.next(); !_c.done; _c = _b.next()) {
                var user = _c.value;
                user.authLabel = getAuthLabel(user);
                user.authLabelStyle = getAuthLabelStyle(user.authLabel);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    return AdminListUsersCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (AdminListUsersCtrl);
function getAuthLabel(user) {
    if (user.authLabels && user.authLabels.length) {
        return user.authLabels[0];
    }
    return '';
}
function getAuthLabelStyle(label) {
    if (label === 'LDAP' || !label) {
        return {};
    }
    var _a = app_core_utils_tags__WEBPACK_IMPORTED_MODULE_1__["default"].getTagColorsFromName(label), color = _a.color, borderColor = _a.borderColor;
    return {
        'background-color': color,
        'border-color': borderColor,
    };
}


/***/ }),

/***/ "./public/app/features/admin/StyleGuideCtrl.ts":
/*!*****************************************************!*\
  !*** ./public/app/features/admin/StyleGuideCtrl.ts ***!
  \*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");

var StyleGuideCtrl = /** @class */ (function () {
    /** @ngInject */
    function StyleGuideCtrl($routeParams, backendSrv, navModelSrv) {
        this.$routeParams = $routeParams;
        this.backendSrv = backendSrv;
        this.buttonNames = ['primary', 'secondary', 'inverse', 'success', 'warning', 'danger'];
        this.buttonSizes = ['btn-small', '', 'btn-large'];
        this.buttonVariants = ['-'];
        this.navModel = navModelSrv.getNav('admin', 'styleguide', 0);
        this.theme = app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData.user.lightTheme ? 'light' : 'dark';
    }
    StyleGuideCtrl.prototype.switchTheme = function () {
        this.$routeParams.theme = this.theme === 'dark' ? 'light' : 'dark';
        var cmd = {
            theme: this.$routeParams.theme,
        };
        this.backendSrv.put('/api/user/preferences', cmd).then(function () {
            window.location.href = window.location.href;
        });
    };
    return StyleGuideCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (StyleGuideCtrl);


/***/ }),

/***/ "./public/app/features/admin/index.ts":
/*!********************************************!*\
  !*** ./public/app/features/admin/index.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AdminListUsersCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AdminListUsersCtrl */ "./public/app/features/admin/AdminListUsersCtrl.ts");
/* harmony import */ var _AdminEditUserCtrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AdminEditUserCtrl */ "./public/app/features/admin/AdminEditUserCtrl.ts");
/* harmony import */ var _AdminListOrgsCtrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AdminListOrgsCtrl */ "./public/app/features/admin/AdminListOrgsCtrl.ts");
/* harmony import */ var _AdminEditOrgCtrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./AdminEditOrgCtrl */ "./public/app/features/admin/AdminEditOrgCtrl.ts");
/* harmony import */ var _StyleGuideCtrl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./StyleGuideCtrl */ "./public/app/features/admin/StyleGuideCtrl.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");






var AdminSettingsCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdminSettingsCtrl($scope, backendSrv, navModelSrv) {
        this.navModel = navModelSrv.getNav('admin', 'server-settings', 0);
        backendSrv.get('/api/admin/settings').then(function (settings) {
            $scope.settings = settings;
        });
    }
    return AdminSettingsCtrl;
}());
var AdminHomeCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdminHomeCtrl(navModelSrv) {
        this.navModel = navModelSrv.getNav('admin');
    }
    return AdminHomeCtrl;
}());
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('AdminListUsersCtrl', _AdminListUsersCtrl__WEBPACK_IMPORTED_MODULE_0__["default"]);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('AdminEditUserCtrl', _AdminEditUserCtrl__WEBPACK_IMPORTED_MODULE_1__["default"]);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('AdminListOrgsCtrl', _AdminListOrgsCtrl__WEBPACK_IMPORTED_MODULE_2__["default"]);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('AdminEditOrgCtrl', _AdminEditOrgCtrl__WEBPACK_IMPORTED_MODULE_3__["default"]);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('AdminSettingsCtrl', AdminSettingsCtrl);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('AdminHomeCtrl', AdminHomeCtrl);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('StyleGuideCtrl', _StyleGuideCtrl__WEBPACK_IMPORTED_MODULE_4__["default"]);


/***/ }),

/***/ "./public/app/features/admin/ldap/LdapConnectionStatus.tsx":
/*!*****************************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapConnectionStatus.tsx ***!
  \*****************************************************************/
/*! exports provided: LdapConnectionStatus, LdapErrorBox */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapConnectionStatus", function() { return LdapConnectionStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapErrorBox", function() { return LdapErrorBox; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/components/AlertBox/AlertBox */ "./public/app/core/components/AlertBox/AlertBox.tsx");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");



var LdapConnectionStatus = function (_a) {
    var ldapConnectionInfo = _a.ldapConnectionInfo;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h3", { className: "page-heading" }, "LDAP Connection"),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", { className: "filter-table form-inline" },
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("thead", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "Host"),
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", { colSpan: 2 }, "Port"))),
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null, ldapConnectionInfo &&
                        ldapConnectionInfo.map(function (serverInfo, index) { return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", { key: index },
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, serverInfo.host),
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, serverInfo.port),
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, serverInfo.available ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-fw fa-check pull-right" })) : (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-fw fa-exclamation-triangle pull-right" }))))); })))),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(LdapErrorBox, { ldapConnectionInfo: ldapConnectionInfo })))));
};
var LdapErrorBox = function (_a) {
    var ldapConnectionInfo = _a.ldapConnectionInfo;
    var hasError = ldapConnectionInfo.some(function (info) { return info.error; });
    if (!hasError) {
        return null;
    }
    var connectionErrors = [];
    ldapConnectionInfo.forEach(function (info) {
        if (info.error) {
            connectionErrors.push(info);
        }
    });
    var errorElements = connectionErrors.map(function (info, index) { return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { key: index },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { style: { fontWeight: 500 } },
            info.host,
            ":",
            info.port,
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null)),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, info.error),
        index !== connectionErrors.length - 1 && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null))))); });
    return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_1__["AlertBox"], { title: "Connection error", severity: app_types__WEBPACK_IMPORTED_MODULE_2__["AppNotificationSeverity"].Error, body: errorElements });
};


/***/ }),

/***/ "./public/app/features/admin/ldap/LdapPage.tsx":
/*!*****************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapPage.tsx ***!
  \*****************************************************/
/*! exports provided: LdapPage, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapPage", function() { return LdapPage; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_hot_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-hot-loader */ "./node_modules/react-hot-loader/index.js");
/* harmony import */ var react_hot_loader__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_hot_loader__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_selectors_navModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/selectors/navModel */ "./public/app/core/selectors/navModel.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_components_Page_Page__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/components/Page/Page */ "./public/app/core/components/Page/Page.tsx");
/* harmony import */ var app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/components/AlertBox/AlertBox */ "./public/app/core/components/AlertBox/AlertBox.tsx");
/* harmony import */ var _LdapConnectionStatus__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./LdapConnectionStatus */ "./public/app/features/admin/ldap/LdapConnectionStatus.tsx");
/* harmony import */ var _LdapSyncInfo__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./LdapSyncInfo */ "./public/app/features/admin/ldap/LdapSyncInfo.tsx");
/* harmony import */ var _LdapUserInfo__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./LdapUserInfo */ "./public/app/features/admin/ldap/LdapUserInfo.tsx");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var _state_actions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../state/actions */ "./public/app/features/admin/state/actions.ts");














var LdapPage = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LdapPage, _super);
    function LdapPage() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isLoading: true,
        };
        _this.search = function (event) {
            event.preventDefault();
            var username = event.target.elements['username'].value;
            if (username) {
                _this.fetchUserMapping(username);
            }
        };
        _this.onClearUserError = function () {
            _this.props.clearUserError();
        };
        return _this;
    }
    LdapPage.prototype.componentDidMount = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.props.clearUserMappingInfo()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.fetchLDAPStatus()];
                    case 2:
                        _a.sent();
                        this.setState({ isLoading: false });
                        return [2 /*return*/];
                }
            });
        });
    };
    LdapPage.prototype.fetchLDAPStatus = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var _a, loadLdapState, loadLdapSyncStatus;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
                _a = this.props, loadLdapState = _a.loadLdapState, loadLdapSyncStatus = _a.loadLdapSyncStatus;
                return [2 /*return*/, Promise.all([loadLdapState(), loadLdapSyncStatus()])];
            });
        });
    };
    LdapPage.prototype.fetchUserMapping = function (username) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var loadUserMapping;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        loadUserMapping = this.props.loadUserMapping;
                        return [4 /*yield*/, loadUserMapping(username)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    LdapPage.prototype.render = function () {
        var _a = this.props, ldapUser = _a.ldapUser, userError = _a.userError, ldapError = _a.ldapError, ldapSyncInfo = _a.ldapSyncInfo, ldapConnectionInfo = _a.ldapConnectionInfo, navModel = _a.navModel;
        var isLoading = this.state.isLoading;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Page_Page__WEBPACK_IMPORTED_MODULE_7__["default"], { navModel: navModel },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Page_Page__WEBPACK_IMPORTED_MODULE_7__["default"].Contents, { isLoading: isLoading },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                    ldapError && ldapError.title && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_8__["AlertBox"], { title: ldapError.title, severity: app_types__WEBPACK_IMPORTED_MODULE_12__["AppNotificationSeverity"].Error, body: ldapError.body }))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LdapConnectionStatus__WEBPACK_IMPORTED_MODULE_9__["LdapConnectionStatus"], { ldapConnectionInfo: ldapConnectionInfo }),
                    app_core_config__WEBPACK_IMPORTED_MODULE_6__["default"].buildInfo.isEnterprise && ldapSyncInfo && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LdapSyncInfo__WEBPACK_IMPORTED_MODULE_10__["LdapSyncInfo"], { ldapSyncInfo: ldapSyncInfo }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "page-heading" }, "Test user mapping"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", { onSubmit: this.search, className: "gf-form-inline" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["FormField"], { label: "Username", labelWidth: 8, inputWidth: 30, type: "text", id: "username", name: "username" }),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { type: "submit", className: "btn btn-primary" }, "Run"))),
                    userError && userError.title && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_8__["AlertBox"], { title: userError.title, severity: app_types__WEBPACK_IMPORTED_MODULE_12__["AppNotificationSeverity"].Error, body: userError.body, onClose: this.onClearUserError }))),
                    ldapUser && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LdapUserInfo__WEBPACK_IMPORTED_MODULE_11__["LdapUserInfo"], { ldapUser: ldapUser, showAttributeMapping: true })))));
    };
    return LdapPage;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var mapStateToProps = function (state) { return ({
    navModel: Object(app_core_selectors_navModel__WEBPACK_IMPORTED_MODULE_5__["getNavModel"])(state.navIndex, 'ldap'),
    ldapConnectionInfo: state.ldap.connectionInfo,
    ldapUser: state.ldap.user,
    ldapSyncInfo: state.ldap.syncInfo,
    userError: state.ldap.userError,
    ldapError: state.ldap.ldapError,
}); };
var mapDispatchToProps = {
    loadLdapState: _state_actions__WEBPACK_IMPORTED_MODULE_13__["loadLdapState"],
    loadLdapSyncStatus: _state_actions__WEBPACK_IMPORTED_MODULE_13__["loadLdapSyncStatus"],
    loadUserMapping: _state_actions__WEBPACK_IMPORTED_MODULE_13__["loadUserMapping"],
    clearUserError: _state_actions__WEBPACK_IMPORTED_MODULE_13__["clearUserError"],
    clearUserMappingInfo: _state_actions__WEBPACK_IMPORTED_MODULE_13__["clearUserMappingInfo"],
};
/* harmony default export */ __webpack_exports__["default"] = (Object(react_hot_loader__WEBPACK_IMPORTED_MODULE_2__["hot"])(module)(Object(react_redux__WEBPACK_IMPORTED_MODULE_3__["connect"])(mapStateToProps, mapDispatchToProps)(LdapPage)));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../../node_modules/webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module)))

/***/ }),

/***/ "./public/app/features/admin/ldap/LdapSyncInfo.tsx":
/*!*********************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapSyncInfo.tsx ***!
  \*********************************************************/
/*! exports provided: LdapSyncInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapSyncInfo", function() { return LdapSyncInfo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");



var syncTimeFormat = 'dddd YYYY-MM-DD HH:mm zz';
var LdapSyncInfo = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LdapSyncInfo, _super);
    function LdapSyncInfo() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isSyncing: false,
        };
        _this.handleSyncClick = function () {
            console.log('Bulk-sync now');
            _this.setState({ isSyncing: !_this.state.isSyncing });
        };
        return _this;
    }
    LdapSyncInfo.prototype.render = function () {
        var ldapSyncInfo = this.props.ldapSyncInfo;
        var isSyncing = this.state.isSyncing;
        var nextSyncTime = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(ldapSyncInfo.nextSync).format(syncTimeFormat);
        var prevSyncSuccessful = ldapSyncInfo && ldapSyncInfo.prevSync;
        var prevSyncTime = prevSyncSuccessful ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(ldapSyncInfo.prevSync.started).format(syncTimeFormat) : '';
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "page-heading" },
                "LDAP Synchronisation",
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn btn-secondary pull-right", onClick: this.handleSyncClick, hidden: true },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "btn-title" }, "Bulk-sync now"),
                    isSyncing && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-spinner fa-fw fa-spin run-icon" }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("table", { className: "filter-table form-inline" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tbody", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, "Active synchronisation"),
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { colSpan: 2 }, ldapSyncInfo.enabled ? 'Enabled' : 'Disabled')),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, "Scheduled"),
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, ldapSyncInfo.schedule)),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, "Next scheduled synchronisation"),
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, nextSyncTime)),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, "Last synchronisation"),
                                prevSyncSuccessful && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, prevSyncTime),
                                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, "Successful"))))))))));
    };
    return LdapSyncInfo;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/features/admin/ldap/LdapUserGroups.tsx":
/*!***********************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapUserGroups.tsx ***!
  \***********************************************************/
/*! exports provided: LdapUserGroups */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapUserGroups", function() { return LdapUserGroups; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


var LdapUserGroups = function (_a) {
    var groups = _a.groups, showAttributeMapping = _a.showAttributeMapping;
    var items = showAttributeMapping ? groups : groups.filter(function (item) { return item.orgRole; });
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", { className: "filter-table form-inline" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("thead", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "LDAP Group"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "Organisation"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "Role"))),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null, items.map(function (group, index) {
                    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", { key: group.orgId + "-" + index },
                        showAttributeMapping && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, group.groupDN),
                            !group.orgRole && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null),
                                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null,
                                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "text-warning" },
                                        "No match",
                                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["Tooltip"], { placement: "top", content: "No matching groups found", theme: 'info' },
                                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "gf-form-help-icon" },
                                                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-info-circle" }))))))))),
                        group.orgName && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, group.orgName),
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, group.orgRole)))));
                }))))));
};


/***/ }),

/***/ "./public/app/features/admin/ldap/LdapUserInfo.tsx":
/*!*********************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapUserInfo.tsx ***!
  \*********************************************************/
/*! exports provided: LdapUserInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapUserInfo", function() { return LdapUserInfo; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _LdapUserMappingInfo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./LdapUserMappingInfo */ "./public/app/features/admin/ldap/LdapUserMappingInfo.tsx");
/* harmony import */ var _LdapUserPermissions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./LdapUserPermissions */ "./public/app/features/admin/ldap/LdapUserPermissions.tsx");
/* harmony import */ var _LdapUserGroups__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LdapUserGroups */ "./public/app/features/admin/ldap/LdapUserGroups.tsx");
/* harmony import */ var _LdapUserTeams__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LdapUserTeams */ "./public/app/features/admin/ldap/LdapUserTeams.tsx");





var LdapUserInfo = function (_a) {
    var ldapUser = _a.ldapUser, showAttributeMapping = _a.showAttributeMapping;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LdapUserMappingInfo__WEBPACK_IMPORTED_MODULE_1__["LdapUserMappingInfo"], { info: ldapUser.info, showAttributeMapping: showAttributeMapping }),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LdapUserPermissions__WEBPACK_IMPORTED_MODULE_2__["LdapUserPermissions"], { permissions: ldapUser.permissions }),
        ldapUser.roles && ldapUser.roles.length > 0 && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LdapUserGroups__WEBPACK_IMPORTED_MODULE_3__["LdapUserGroups"], { groups: ldapUser.roles, showAttributeMapping: showAttributeMapping })),
        ldapUser.teams && ldapUser.teams.length > 0 ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_LdapUserTeams__WEBPACK_IMPORTED_MODULE_4__["LdapUserTeams"], { teams: ldapUser.teams, showAttributeMapping: showAttributeMapping })) : (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", { className: "filter-table form-inline" },
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, "No teams found via LDAP")))))))));
};


/***/ }),

/***/ "./public/app/features/admin/ldap/LdapUserMappingInfo.tsx":
/*!****************************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapUserMappingInfo.tsx ***!
  \****************************************************************/
/*! exports provided: LdapUserMappingInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapUserMappingInfo", function() { return LdapUserMappingInfo; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var LdapUserMappingInfo = function (_a) {
    var info = _a.info, showAttributeMapping = _a.showAttributeMapping;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", { className: "filter-table form-inline" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("thead", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", { colSpan: 2 }, "User information"),
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "LDAP attribute"))),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", { className: "width-16" }, "First name"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.name.ldapValue),
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.name.cfgAttrValue)),
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", { className: "width-16" }, "Surname"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.surname.ldapValue),
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.surname.cfgAttrValue)),
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", { className: "width-16" }, "Username"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.login.ldapValue),
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.login.cfgAttrValue)),
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", { className: "width-16" }, "Email"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.email.ldapValue),
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, info.email.cfgAttrValue)))))));
};


/***/ }),

/***/ "./public/app/features/admin/ldap/LdapUserPermissions.tsx":
/*!****************************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapUserPermissions.tsx ***!
  \****************************************************************/
/*! exports provided: LdapUserPermissions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapUserPermissions", function() { return LdapUserPermissions; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var LdapUserPermissions = function (_a) {
    var permissions = _a.permissions;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", { className: "filter-table form-inline" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("thead", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", { colSpan: 1 }, "Permissions"))),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", { className: "width-16" }, " Grafana admin"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, permissions.isGrafanaAdmin ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "gicon gicon-shield" }),
                            " Yes")) : ('No'))),
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", { className: "width-16" }, "Status"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, permissions.isDisabled ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-fw fa-times" }),
                            " Inactive")) : (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-fw fa-check" }),
                            " Active")))))))));
};


/***/ }),

/***/ "./public/app/features/admin/ldap/LdapUserTeams.tsx":
/*!**********************************************************!*\
  !*** ./public/app/features/admin/ldap/LdapUserTeams.tsx ***!
  \**********************************************************/
/*! exports provided: LdapUserTeams */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LdapUserTeams", function() { return LdapUserTeams; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


var LdapUserTeams = function (_a) {
    var teams = _a.teams, showAttributeMapping = _a.showAttributeMapping;
    var items = showAttributeMapping ? teams : teams.filter(function (item) { return item.teamName; });
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("table", { className: "filter-table form-inline" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("thead", null,
                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", null,
                        showAttributeMapping && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "LDAP Group"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "Organisation"),
                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("th", null, "Team"))),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tbody", null, items.map(function (team, index) {
                    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("tr", { key: team.teamName + "-" + index },
                        showAttributeMapping && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, team.groupDN),
                            !team.orgName && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null),
                                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null,
                                    react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "text-warning" },
                                        "No match",
                                        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["Tooltip"], { placement: "top", content: "No matching teams found", theme: 'info' },
                                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "gf-form-help-icon" },
                                                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "fa fa-info-circle" }))))))))),
                        team.orgName && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, team.orgName),
                            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("td", null, team.teamName)))));
                }))))));
};


/***/ }),

/***/ "./public/app/features/admin/state/actions.ts":
/*!****************************************************!*\
  !*** ./public/app/features/admin/state/actions.ts ***!
  \****************************************************/
/*! exports provided: ldapConnectionInfoLoadedAction, ldapSyncStatusLoadedAction, userMappingInfoLoadedAction, userMappingInfoFailedAction, clearUserMappingInfoAction, clearUserErrorAction, ldapFailedAction, userLoadedAction, userSessionsLoadedAction, userSyncFailedAction, revokeUserSessionAction, revokeAllUserSessionsAction, loadLdapState, loadLdapSyncStatus, loadUserMapping, clearUserError, clearUserMappingInfo, syncUser, loadLdapUserInfo, loadUserSessions, revokeSession, revokeAllSessions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ldapConnectionInfoLoadedAction", function() { return ldapConnectionInfoLoadedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ldapSyncStatusLoadedAction", function() { return ldapSyncStatusLoadedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "userMappingInfoLoadedAction", function() { return userMappingInfoLoadedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "userMappingInfoFailedAction", function() { return userMappingInfoFailedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearUserMappingInfoAction", function() { return clearUserMappingInfoAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearUserErrorAction", function() { return clearUserErrorAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ldapFailedAction", function() { return ldapFailedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "userLoadedAction", function() { return userLoadedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "userSessionsLoadedAction", function() { return userSessionsLoadedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "userSyncFailedAction", function() { return userSyncFailedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeUserSessionAction", function() { return revokeUserSessionAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeAllUserSessionsAction", function() { return revokeAllUserSessionsAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadLdapState", function() { return loadLdapState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadLdapSyncStatus", function() { return loadLdapSyncStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadUserMapping", function() { return loadUserMapping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearUserError", function() { return clearUserError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearUserMappingInfo", function() { return clearUserMappingInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "syncUser", function() { return syncUser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadLdapUserInfo", function() { return loadLdapUserInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadUserSessions", function() { return loadUserSessions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeSession", function() { return revokeSession; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeAllSessions", function() { return revokeAllSessions; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _apis__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./apis */ "./public/app/features/admin/state/apis.ts");




// Action types
var ldapConnectionInfoLoadedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('ldap/CONNECTION_INFO_LOADED').create();
var ldapSyncStatusLoadedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('ldap/SYNC_STATUS_LOADED').create();
var userMappingInfoLoadedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('ldap/USER_INFO_LOADED').create();
var userMappingInfoFailedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('ldap/USER_INFO_FAILED').create();
var clearUserMappingInfoAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["noPayloadActionCreatorFactory"])('ldap/CLEAR_USER_MAPPING_INFO').create();
var clearUserErrorAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["noPayloadActionCreatorFactory"])('ldap/CLEAR_USER_ERROR').create();
var ldapFailedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('ldap/LDAP_FAILED').create();
var userLoadedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('USER_LOADED').create();
var userSessionsLoadedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('USER_SESSIONS_LOADED').create();
var userSyncFailedAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["noPayloadActionCreatorFactory"])('USER_SYNC_FAILED').create();
var revokeUserSessionAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["noPayloadActionCreatorFactory"])('REVOKE_USER_SESSION').create();
var revokeAllUserSessionsAction = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["noPayloadActionCreatorFactory"])('REVOKE_ALL_USER_SESSIONS').create();
// Actions
function loadLdapState() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var connectionInfo, error_1, ldapError;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["getLdapState"])()];
                case 1:
                    connectionInfo = _a.sent();
                    dispatch(ldapConnectionInfoLoadedAction(connectionInfo));
                    return [3 /*break*/, 3];
                case 2:
                    error_1 = _a.sent();
                    error_1.isHandled = true;
                    ldapError = {
                        title: error_1.data.message,
                        body: error_1.data.error,
                    };
                    dispatch(ldapFailedAction(ldapError));
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); };
}
function loadLdapSyncStatus() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var syncStatus;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].buildInfo.isEnterprise) return [3 /*break*/, 2];
                    return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["getLdapSyncStatus"])()];
                case 1:
                    syncStatus = _a.sent();
                    dispatch(ldapSyncStatusLoadedAction(syncStatus));
                    _a.label = 2;
                case 2: return [2 /*return*/];
            }
        });
    }); };
}
function loadUserMapping(username) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var userInfo, error_2, userError;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["getUserInfo"])(username)];
                case 1:
                    userInfo = _a.sent();
                    dispatch(userMappingInfoLoadedAction(userInfo));
                    return [3 /*break*/, 3];
                case 2:
                    error_2 = _a.sent();
                    error_2.isHandled = true;
                    userError = {
                        title: error_2.data.message,
                        body: error_2.data.error,
                    };
                    dispatch(clearUserMappingInfoAction());
                    dispatch(userMappingInfoFailedAction(userError));
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); };
}
function clearUserError() {
    return function (dispatch) {
        dispatch(clearUserErrorAction());
    };
}
function clearUserMappingInfo() {
    return function (dispatch) {
        dispatch(clearUserErrorAction());
        dispatch(clearUserMappingInfoAction());
    };
}
function syncUser(userId) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var error_3;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["syncLdapUser"])(userId)];
                case 1:
                    _a.sent();
                    dispatch(loadLdapUserInfo(userId));
                    dispatch(loadLdapSyncStatus());
                    return [3 /*break*/, 3];
                case 2:
                    error_3 = _a.sent();
                    dispatch(userSyncFailedAction());
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); };
}
function loadLdapUserInfo(userId) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var user, error_4, userError;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["getUser"])(userId)];
                case 1:
                    user = _a.sent();
                    dispatch(userLoadedAction(user));
                    dispatch(loadUserSessions(userId));
                    dispatch(loadUserMapping(user.login));
                    return [3 /*break*/, 3];
                case 2:
                    error_4 = _a.sent();
                    error_4.isHandled = true;
                    userError = {
                        title: error_4.data.message,
                        body: error_4.data.error,
                    };
                    dispatch(userMappingInfoFailedAction(userError));
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); };
}
function loadUserSessions(userId) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var sessions;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["getUserSessions"])(userId)];
                case 1:
                    sessions = _a.sent();
                    dispatch(userSessionsLoadedAction(sessions));
                    return [2 /*return*/];
            }
        });
    }); };
}
function revokeSession(tokenId, userId) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["revokeUserSession"])(tokenId, userId)];
                case 1:
                    _a.sent();
                    dispatch(loadUserSessions(userId));
                    return [2 /*return*/];
            }
        });
    }); };
}
function revokeAllSessions(userId) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_apis__WEBPACK_IMPORTED_MODULE_3__["revokeAllUserSessions"])(userId)];
                case 1:
                    _a.sent();
                    dispatch(loadUserSessions(userId));
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/admin/state/apis.ts":
/*!*************************************************!*\
  !*** ./public/app/features/admin/state/apis.ts ***!
  \*************************************************/
/*! exports provided: getServerStats, getLdapState, getLdapSyncStatus, syncLdapUser, getUserInfo, getUser, getUserSessions, revokeUserSession, revokeAllUserSessions */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getServerStats", function() { return getServerStats; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLdapState", function() { return getLdapState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLdapSyncStatus", function() { return getLdapSyncStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "syncLdapUser", function() { return syncLdapUser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUserInfo", function() { return getUserInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUser", function() { return getUser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getUserSessions", function() { return getUserSessions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeUserSession", function() { return revokeUserSession; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeAllUserSessions", function() { return revokeAllUserSessions; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
var _this = undefined;



var getServerStats = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
    var res, error_1;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 2, , 3]);
                return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('api/admin/stats')];
            case 1:
                res = _a.sent();
                return [2 /*return*/, [
                        { name: 'Total users', value: res.users },
                        { name: 'Total admins', value: res.admins },
                        { name: 'Total editors', value: res.editors },
                        { name: 'Total viewers', value: res.viewers },
                        { name: 'Active users (seen last 30 days)', value: res.activeUsers },
                        { name: 'Active admins (seen last 30 days)', value: res.activeAdmins },
                        { name: 'Active editors (seen last 30 days)', value: res.activeEditors },
                        { name: 'Active viewers (seen last 30 days)', value: res.activeViewers },
                        { name: 'Active sessions', value: res.activeSessions },
                        { name: 'Total dashboards', value: res.dashboards },
                        { name: 'Total orgs', value: res.orgs },
                        { name: 'Total playlists', value: res.playlists },
                        { name: 'Total snapshots', value: res.snapshots },
                        { name: 'Total dashboard tags', value: res.tags },
                        { name: 'Total starred dashboards', value: res.stars },
                        { name: 'Total alerts', value: res.alerts },
                    ]];
            case 2:
                error_1 = _a.sent();
                console.error(error_1);
                throw error_1;
            case 3: return [2 /*return*/];
        }
    });
}); };
var getLdapState = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/admin/ldap/status")];
            case 1: return [2 /*return*/, _a.sent()];
        }
    });
}); };
var getLdapSyncStatus = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/admin/ldap-sync-status")];
            case 1: return [2 /*return*/, _a.sent()];
        }
    });
}); };
var syncLdapUser = function (userId) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/admin/ldap/sync/" + userId)];
            case 1: return [2 /*return*/, _a.sent()];
        }
    });
}); };
var getUserInfo = function (username) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
    var response, name, surname, email, login, isGrafanaAdmin, isDisabled, roles, teams;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/admin/ldap/" + username)];
            case 1:
                response = _a.sent();
                name = response.name, surname = response.surname, email = response.email, login = response.login, isGrafanaAdmin = response.isGrafanaAdmin, isDisabled = response.isDisabled, roles = response.roles, teams = response.teams;
                return [2 /*return*/, {
                        info: { name: name, surname: surname, email: email, login: login },
                        permissions: { isGrafanaAdmin: isGrafanaAdmin, isDisabled: isDisabled },
                        roles: roles,
                        teams: teams,
                    }];
        }
    });
}); };
var getUser = function (id) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/users/' + id)];
            case 1: return [2 /*return*/, _a.sent()];
        }
    });
}); };
var getUserSessions = function (id) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    var sessions;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/admin/users/' + id + '/auth-tokens')];
            case 1:
                sessions = _a.sent();
                sessions.reverse();
                return [2 /*return*/, sessions.map(function (session) {
                        return {
                            id: session.id,
                            isActive: session.isActive,
                            seenAt: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(session.seenAt).fromNow(),
                            createdAt: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(session.createdAt).format('MMMM DD, YYYY'),
                            clientIp: session.clientIp,
                            browser: session.browser,
                            browserVersion: session.browserVersion,
                            os: session.os,
                            osVersion: session.osVersion,
                            device: session.device,
                        };
                    })];
        }
    });
}); };
var revokeUserSession = function (tokenId, userId) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/admin/users/" + userId + "/revoke-auth-token", {
                    authTokenId: tokenId,
                })];
            case 1: return [2 /*return*/, _a.sent()];
        }
    });
}); };
var revokeAllUserSessions = function (userId) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/admin/users/" + userId + "/logout")];
            case 1: return [2 /*return*/, _a.sent()];
        }
    });
}); };


/***/ }),

/***/ "./public/app/features/admin/state/reducers.ts":
/*!*****************************************************!*\
  !*** ./public/app/features/admin/state/reducers.ts ***!
  \*****************************************************/
/*! exports provided: ldapReducer, ldapUserReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ldapReducer", function() { return ldapReducer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ldapUserReducer", function() { return ldapUserReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./actions */ "./public/app/features/admin/state/actions.ts");



var initialLdapState = {
    connectionInfo: [],
    syncInfo: null,
    user: null,
    connectionError: null,
    userError: null,
};
var initialLdapUserState = {
    user: null,
    ldapUser: null,
    ldapSyncInfo: null,
    sessions: [],
};
var ldapReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["reducerFactory"])(initialLdapState)
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["ldapConnectionInfoLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { ldapError: null, connectionInfo: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["ldapFailedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { ldapError: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["ldapSyncStatusLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { syncInfo: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["userMappingInfoLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { user: action.payload, userError: null })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["userMappingInfoFailedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { user: null, userError: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["clearUserMappingInfoAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { user: null })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["clearUserErrorAction"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { userError: null })); },
})
    .create();
var ldapUserReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_1__["reducerFactory"])(initialLdapUserState)
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["userMappingInfoLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { ldapUser: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["userMappingInfoFailedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { ldapUser: null, userError: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["clearUserErrorAction"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { userError: null })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["ldapSyncStatusLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { ldapSyncInfo: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["userLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { user: action.payload, userError: null })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["userSessionsLoadedAction"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { sessions: action.payload })); },
})
    .create();
/* harmony default export */ __webpack_exports__["default"] = ({
    ldap: ldapReducer,
    ldapUser: ldapUserReducer,
});


/***/ }),

/***/ "./public/app/features/alerting/AlertTabCtrl.ts":
/*!******************************************************!*\
  !*** ./public/app/features/alerting/AlertTabCtrl.ts ***!
  \******************************************************/
/*! exports provided: AlertTabCtrl, alertTab */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertTabCtrl", function() { return AlertTabCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alertTab", function() { return alertTab; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _state_ThresholdMapper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./state/ThresholdMapper */ "./public/app/features/alerting/state/ThresholdMapper.ts");
/* harmony import */ var app_core_components_query_part_query_part__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/components/query_part/query_part */ "./public/app/core/components/query_part/query_part.ts");
/* harmony import */ var _state_alertDef__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./state/alertDef */ "./public/app/features/alerting/state/alertDef.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var _getAlertingValidationMessage__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./getAlertingValidationMessage */ "./public/app/features/alerting/getAlertingValidationMessage.ts");









var AlertTabCtrl = /** @class */ (function () {
    /** @ngInject */
    function AlertTabCtrl($scope, backendSrv, dashboardSrv, uiSegmentSrv, $q, datasourceSrv) {
        var _this = this;
        this.$scope = $scope;
        this.backendSrv = backendSrv;
        this.dashboardSrv = dashboardSrv;
        this.uiSegmentSrv = uiSegmentSrv;
        this.$q = $q;
        this.datasourceSrv = datasourceSrv;
        this.enable = function () {
            _this.panel.alert = {};
            _this.initModel();
            _this.panel.alert.for = '5m'; //default value for new alerts. for existing alerts we use 0m to avoid breaking changes
        };
        this.panelCtrl = $scope.ctrl;
        this.panel = this.panelCtrl.panel;
        this.$scope.ctrl = this;
        this.subTabIndex = 0;
        this.evalFunctions = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].evalFunctions;
        this.evalOperators = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].evalOperators;
        this.conditionTypes = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].conditionTypes;
        this.noDataModes = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].noDataModes;
        this.executionErrorModes = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].executionErrorModes;
        this.appSubUrl = app_core_config__WEBPACK_IMPORTED_MODULE_6__["default"].appSubUrl;
        this.panelCtrl._enableAlert = this.enable;
    }
    AlertTabCtrl.prototype.$onInit = function () {
        var _this = this;
        this.addNotificationSegment = this.uiSegmentSrv.newPlusButton();
        // subscribe to graph threshold handle changes
        var thresholdChangedEventHandler = this.graphThresholdChanged.bind(this);
        this.panelCtrl.events.on('threshold-changed', thresholdChangedEventHandler);
        // set panel alert edit mode
        this.$scope.$on('$destroy', function () {
            _this.panelCtrl.events.off('threshold-changed', thresholdChangedEventHandler);
            _this.panelCtrl.editingThresholds = false;
            _this.panelCtrl.render();
        });
        // build notification model
        this.notifications = [];
        this.alertNotifications = [];
        this.alertHistory = [];
        return this.backendSrv.get('/api/alert-notifications/lookup').then(function (res) {
            _this.notifications = res;
            _this.initModel();
            _this.validateModel();
        });
    };
    AlertTabCtrl.prototype.getAlertHistory = function () {
        var _this = this;
        this.backendSrv
            .get("/api/annotations?dashboardId=" + this.panelCtrl.dashboard.id + "&panelId=" + this.panel.id + "&limit=50&type=alert")
            .then(function (res) {
            _this.alertHistory = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(res, function (ah) {
                ah.time = _this.dashboardSrv.getCurrent().formatDate(ah.time, 'MMM D, YYYY HH:mm:ss');
                ah.stateModel = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].getStateDisplayModel(ah.newState);
                ah.info = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].getAlertAnnotationInfo(ah);
                return ah;
            });
        });
    };
    AlertTabCtrl.prototype.getNotificationIcon = function (type) {
        switch (type) {
            case 'email':
                return 'fa fa-envelope';
            case 'slack':
                return 'fa fa-slack';
            case 'victorops':
                return 'fa fa-pagelines';
            case 'webhook':
                return 'fa fa-cubes';
            case 'pagerduty':
                return 'fa fa-bullhorn';
            case 'opsgenie':
                return 'fa fa-bell';
            case 'hipchat':
                return 'fa fa-mail-forward';
            case 'pushover':
                return 'fa fa-mobile';
            case 'kafka':
                return 'fa fa-random';
            case 'teams':
                return 'fa fa-windows';
        }
        return 'fa fa-bell';
    };
    AlertTabCtrl.prototype.getNotifications = function () {
        var _this = this;
        return this.$q.when(this.notifications.map(function (item) {
            return _this.uiSegmentSrv.newSegment(item.name);
        }));
    };
    AlertTabCtrl.prototype.notificationAdded = function () {
        var model = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.notifications, {
            name: this.addNotificationSegment.value,
        });
        if (!model) {
            return;
        }
        this.alertNotifications.push({
            name: model.name,
            iconClass: this.getNotificationIcon(model.type),
            isDefault: false,
            uid: model.uid,
        });
        // avoid duplicates using both id and uid to be backwards compatible.
        if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.alert.notifications, function (n) { return n.id === model.id || n.uid === model.uid; })) {
            this.alert.notifications.push({ uid: model.uid });
        }
        // reset plus button
        this.addNotificationSegment.value = this.uiSegmentSrv.newPlusButton().value;
        this.addNotificationSegment.html = this.uiSegmentSrv.newPlusButton().html;
        this.addNotificationSegment.fake = true;
    };
    AlertTabCtrl.prototype.removeNotification = function (an) {
        // remove notifiers refeered to by id and uid to support notifiers added
        // before and after we added support for uid
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.remove(this.alert.notifications, function (n) { return n.uid === an.uid || n.id === an.id; });
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.remove(this.alertNotifications, function (n) { return n.uid === an.uid || n.id === an.id; });
    };
    AlertTabCtrl.prototype.addAlertRuleTag = function () {
        if (this.newAlertRuleTag.name) {
            this.alert.alertRuleTags[this.newAlertRuleTag.name] = this.newAlertRuleTag.value;
        }
        this.newAlertRuleTag.name = '';
        this.newAlertRuleTag.value = '';
    };
    AlertTabCtrl.prototype.removeAlertRuleTag = function (tagName) {
        delete this.alert.alertRuleTags[tagName];
    };
    AlertTabCtrl.prototype.initModel = function () {
        var e_1, _a, e_2, _b;
        var _this = this;
        var alert = (this.alert = this.panel.alert);
        if (!alert) {
            return;
        }
        alert.conditions = alert.conditions || [];
        if (alert.conditions.length === 0) {
            alert.conditions.push(Object(_getAlertingValidationMessage__WEBPACK_IMPORTED_MODULE_8__["getDefaultCondition"])());
        }
        alert.noDataState = alert.noDataState || app_core_config__WEBPACK_IMPORTED_MODULE_6__["default"].alertingNoDataOrNullValues;
        alert.executionErrorState = alert.executionErrorState || app_core_config__WEBPACK_IMPORTED_MODULE_6__["default"].alertingErrorOrTimeout;
        alert.frequency = alert.frequency || '1m';
        alert.handler = alert.handler || 1;
        alert.notifications = alert.notifications || [];
        alert.for = alert.for || '0m';
        alert.alertRuleTags = alert.alertRuleTags || {};
        var defaultName = this.panel.title + ' alert';
        alert.name = alert.name || defaultName;
        this.conditionModels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.reduce(alert.conditions, function (memo, value) {
            memo.push(_this.buildConditionModel(value));
            return memo;
        }, []);
        _state_ThresholdMapper__WEBPACK_IMPORTED_MODULE_3__["ThresholdMapper"].alertToGraphThresholds(this.panel);
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](alert.notifications), _d = _c.next(); !_d.done; _d = _c.next()) {
                var addedNotification = _d.value;
                // lookup notifier type by uid
                var model = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.notifications, { uid: addedNotification.uid });
                // fallback to using id if uid is missing
                if (!model) {
                    model = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.notifications, { id: addedNotification.id });
                }
                if (model && model.isDefault === false) {
                    model.iconClass = this.getNotificationIcon(model.type);
                    this.alertNotifications.push(model);
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_1) throw e_1.error; }
        }
        try {
            for (var _e = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.notifications), _f = _e.next(); !_f.done; _f = _e.next()) {
                var notification = _f.value;
                if (notification.isDefault) {
                    notification.iconClass = this.getNotificationIcon(notification.type);
                    notification.bgColor = '#00678b';
                    this.alertNotifications.push(notification);
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
            }
            finally { if (e_2) throw e_2.error; }
        }
        this.panelCtrl.editingThresholds = true;
        this.panelCtrl.render();
    };
    AlertTabCtrl.prototype.graphThresholdChanged = function (evt) {
        var e_3, _a;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.alert.conditions), _c = _b.next(); !_c.done; _c = _b.next()) {
                var condition = _c.value;
                if (condition.type === 'query') {
                    condition.evaluator.params[evt.handleIndex] = evt.threshold.value;
                    this.evaluatorParamsChanged();
                    break;
                }
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
    };
    AlertTabCtrl.prototype.validateModel = function () {
        var e_4, _a, e_5, _b;
        var _this = this;
        if (!this.alert) {
            return;
        }
        var firstTarget;
        var foundTarget = null;
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.alert.conditions), _d = _c.next(); !_d.done; _d = _c.next()) {
                var condition = _d.value;
                if (condition.type !== 'query') {
                    continue;
                }
                try {
                    for (var _e = (e_5 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panel.targets)), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var target = _f.value;
                        if (!firstTarget) {
                            firstTarget = target;
                        }
                        if (condition.query.params[0] === target.refId) {
                            foundTarget = target;
                            break;
                        }
                    }
                }
                catch (e_5_1) { e_5 = { error: e_5_1 }; }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                    }
                    finally { if (e_5) throw e_5.error; }
                }
                if (!foundTarget) {
                    if (firstTarget) {
                        condition.query.params[0] = firstTarget.refId;
                        foundTarget = firstTarget;
                    }
                    else {
                        this.error = 'Could not find any metric queries';
                    }
                }
                var datasourceName = foundTarget.datasource || this.panel.datasource;
                this.datasourceSrv.get(datasourceName).then(function (ds) {
                    if (!ds.meta.alerting) {
                        _this.error = 'The datasource does not support alerting queries';
                    }
                    else if (ds.targetContainsTemplate && ds.targetContainsTemplate(foundTarget)) {
                        _this.error = 'Template variables are not supported in alert queries';
                    }
                    else {
                        _this.error = '';
                    }
                });
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_4) throw e_4.error; }
        }
    };
    AlertTabCtrl.prototype.buildConditionModel = function (source) {
        var cm = { source: source, type: source.type };
        cm.queryPart = new app_core_components_query_part_query_part__WEBPACK_IMPORTED_MODULE_4__["QueryPart"](source.query, _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].alertQueryDef);
        cm.reducerPart = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].createReducerPart(source.reducer);
        cm.evaluator = source.evaluator;
        cm.operator = source.operator;
        return cm;
    };
    AlertTabCtrl.prototype.handleQueryPartEvent = function (conditionModel, evt) {
        var _this = this;
        switch (evt.name) {
            case 'action-remove-part': {
                break;
            }
            case 'get-part-actions': {
                return this.$q.when([]);
            }
            case 'part-param-changed': {
                this.validateModel();
            }
            case 'get-param-options': {
                var result = this.panel.targets.map(function (target) {
                    return _this.uiSegmentSrv.newSegment({ value: target.refId });
                });
                return this.$q.when(result);
            }
        }
    };
    AlertTabCtrl.prototype.handleReducerPartEvent = function (conditionModel, evt) {
        var e_6, _a;
        switch (evt.name) {
            case 'action': {
                conditionModel.source.reducer.type = evt.action.value;
                conditionModel.reducerPart = _state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].createReducerPart(conditionModel.source.reducer);
                break;
            }
            case 'get-part-actions': {
                var result = [];
                try {
                    for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](_state_alertDef__WEBPACK_IMPORTED_MODULE_5__["default"].reducerTypes), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var type = _c.value;
                        if (type.value !== conditionModel.source.reducer.type) {
                            result.push(type);
                        }
                    }
                }
                catch (e_6_1) { e_6 = { error: e_6_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_6) throw e_6.error; }
                }
                return this.$q.when(result);
            }
        }
    };
    AlertTabCtrl.prototype.addCondition = function (type) {
        var condition = Object(_getAlertingValidationMessage__WEBPACK_IMPORTED_MODULE_8__["getDefaultCondition"])();
        // add to persited model
        this.alert.conditions.push(condition);
        // add to view model
        this.conditionModels.push(this.buildConditionModel(condition));
    };
    AlertTabCtrl.prototype.removeCondition = function (index) {
        this.alert.conditions.splice(index, 1);
        this.conditionModels.splice(index, 1);
    };
    AlertTabCtrl.prototype.delete = function () {
        var _this = this;
        app_core_app_events__WEBPACK_IMPORTED_MODULE_7__["default"].emit('confirm-modal', {
            title: 'Delete Alert',
            text: 'Are you sure you want to delete this alert rule?',
            text2: 'You need to save dashboard for the delete to take effect',
            icon: 'fa-trash',
            yesText: 'Delete',
            onConfirm: function () {
                delete _this.panel.alert;
                _this.alert = null;
                _this.panel.thresholds = [];
                _this.conditionModels = [];
                _this.panelCtrl.alertState = null;
                _this.panelCtrl.render();
            },
        });
    };
    AlertTabCtrl.prototype.evaluatorParamsChanged = function () {
        _state_ThresholdMapper__WEBPACK_IMPORTED_MODULE_3__["ThresholdMapper"].alertToGraphThresholds(this.panel);
        this.panelCtrl.render();
    };
    AlertTabCtrl.prototype.evaluatorTypeChanged = function (evaluator) {
        // ensure params array is correct length
        switch (evaluator.type) {
            case 'lt':
            case 'gt': {
                evaluator.params = [evaluator.params[0]];
                break;
            }
            case 'within_range':
            case 'outside_range': {
                evaluator.params = [evaluator.params[0], evaluator.params[1]];
                break;
            }
            case 'no_value': {
                evaluator.params = [];
            }
        }
        this.evaluatorParamsChanged();
    };
    AlertTabCtrl.prototype.clearHistory = function () {
        var _this = this;
        app_core_app_events__WEBPACK_IMPORTED_MODULE_7__["default"].emit('confirm-modal', {
            title: 'Delete Alert History',
            text: 'Are you sure you want to remove all history & annotations for this alert?',
            icon: 'fa-trash',
            yesText: 'Yes',
            onConfirm: function () {
                _this.backendSrv
                    .post('/api/annotations/mass-delete', {
                    dashboardId: _this.panelCtrl.dashboard.id,
                    panelId: _this.panel.id,
                })
                    .then(function () {
                    _this.alertHistory = [];
                    _this.panelCtrl.refresh();
                });
            },
        });
    };
    return AlertTabCtrl;
}());

/** @ngInject */
function alertTab() {
    'use strict';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'public/app/features/alerting/partials/alert_tab.html',
        controller: AlertTabCtrl,
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('alertTab', alertTab);


/***/ }),

/***/ "./public/app/features/alerting/NotificationsEditCtrl.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/alerting/NotificationsEditCtrl.ts ***!
  \***************************************************************/
/*! exports provided: AlertNotificationEditCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertNotificationEditCtrl", function() { return AlertNotificationEditCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");



var AlertNotificationEditCtrl = /** @class */ (function () {
    /** @ngInject */
    function AlertNotificationEditCtrl($routeParams, backendSrv, $location, $templateCache, navModelSrv) {
        var _this = this;
        this.$routeParams = $routeParams;
        this.backendSrv = backendSrv;
        this.$location = $location;
        this.$templateCache = $templateCache;
        this.testSeverity = 'critical';
        this.defaults = {
            type: 'email',
            sendReminder: false,
            disableResolveMessage: false,
            frequency: '15m',
            settings: {
                httpMethod: 'POST',
                autoResolve: true,
                uploadImage: true,
            },
            isDefault: false,
        };
        this.navModel = navModelSrv.getNav('alerting', 'channels', 0);
        this.isNew = !this.$routeParams.id;
        this.getFrequencySuggestion = function () {
            return ['1m', '5m', '10m', '15m', '30m', '1h'];
        };
        this.backendSrv
            .get("/api/alert-notifiers")
            .then(function (notifiers) {
            var e_1, _a;
            _this.notifiers = notifiers;
            try {
                // add option templates
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](_this.notifiers), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var notifier = _c.value;
                    _this.$templateCache.put(_this.getNotifierTemplateId(notifier.type), notifier.optionsTemplate);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            if (!_this.$routeParams.id) {
                _this.navModel.breadcrumbs.push({ text: 'New channel' });
                _this.navModel.node = { text: 'New channel' };
                return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.model, _this.defaults);
            }
            return _this.backendSrv.get("/api/alert-notifications/" + _this.$routeParams.id).then(function (result) {
                _this.navModel.breadcrumbs.push({ text: result.name });
                _this.navModel.node = { text: result.name };
                result.settings = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(result.settings, _this.defaults.settings);
                return result;
            });
        })
            .then(function (model) {
            _this.model = model;
            _this.notifierTemplateId = _this.getNotifierTemplateId(_this.model.type);
        });
    }
    AlertNotificationEditCtrl.prototype.save = function () {
        var _this = this;
        if (!this.theForm.$valid) {
            return;
        }
        if (this.model.id) {
            this.backendSrv
                .put("/api/alert-notifications/" + this.model.id, this.model)
                .then(function (res) {
                _this.model = res;
                app_core_core__WEBPACK_IMPORTED_MODULE_2__["appEvents"].emit('alert-success', ['Notification updated', '']);
            })
                .catch(function (err) {
                if (err.data && err.data.error) {
                    app_core_core__WEBPACK_IMPORTED_MODULE_2__["appEvents"].emit('alert-error', [err.data.error]);
                }
            });
        }
        else {
            this.backendSrv
                .post("/api/alert-notifications", this.model)
                .then(function (res) {
                app_core_core__WEBPACK_IMPORTED_MODULE_2__["appEvents"].emit('alert-success', ['Notification created', '']);
                _this.$location.path('alerting/notifications');
            })
                .catch(function (err) {
                if (err.data && err.data.error) {
                    app_core_core__WEBPACK_IMPORTED_MODULE_2__["appEvents"].emit('alert-error', [err.data.error]);
                }
            });
        }
    };
    AlertNotificationEditCtrl.prototype.deleteNotification = function () {
        var _this = this;
        this.backendSrv.delete("/api/alert-notifications/" + this.model.id).then(function (res) {
            _this.model = res;
            _this.$location.path('alerting/notifications');
        });
    };
    AlertNotificationEditCtrl.prototype.getNotifierTemplateId = function (type) {
        return "notifier-options-" + type;
    };
    AlertNotificationEditCtrl.prototype.typeChanged = function () {
        this.model.settings = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults({}, this.defaults.settings);
        this.notifierTemplateId = this.getNotifierTemplateId(this.model.type);
    };
    AlertNotificationEditCtrl.prototype.testNotification = function () {
        if (!this.theForm.$valid) {
            return;
        }
        var payload = {
            name: this.model.name,
            type: this.model.type,
            frequency: this.model.frequency,
            settings: this.model.settings,
        };
        this.backendSrv.post("/api/alert-notifications/test", payload);
    };
    return AlertNotificationEditCtrl;
}());

app_core_core__WEBPACK_IMPORTED_MODULE_2__["coreModule"].controller('AlertNotificationEditCtrl', AlertNotificationEditCtrl);


/***/ }),

/***/ "./public/app/features/alerting/NotificationsListCtrl.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/alerting/NotificationsListCtrl.ts ***!
  \***************************************************************/
/*! exports provided: AlertNotificationsListCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertNotificationsListCtrl", function() { return AlertNotificationsListCtrl; });
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");

var AlertNotificationsListCtrl = /** @class */ (function () {
    /** @ngInject */
    function AlertNotificationsListCtrl(backendSrv, navModelSrv) {
        this.backendSrv = backendSrv;
        this.loadNotifications();
        this.navModel = navModelSrv.getNav('alerting', 'channels', 0);
    }
    AlertNotificationsListCtrl.prototype.loadNotifications = function () {
        var _this = this;
        this.backendSrv.get("/api/alert-notifications").then(function (result) {
            _this.notifications = result;
        });
    };
    AlertNotificationsListCtrl.prototype.deleteNotification = function (id) {
        var _this = this;
        this.backendSrv.delete("/api/alert-notifications/" + id).then(function () {
            _this.notifications = _this.notifications.filter(function (notification) {
                return notification.id !== id;
            });
        });
    };
    return AlertNotificationsListCtrl;
}());

app_core_core__WEBPACK_IMPORTED_MODULE_0__["coreModule"].controller('AlertNotificationsListCtrl', AlertNotificationsListCtrl);


/***/ }),

/***/ "./public/app/features/alerting/getAlertingValidationMessage.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/alerting/getAlertingValidationMessage.ts ***!
  \**********************************************************************/
/*! exports provided: getDefaultCondition, getAlertingValidationMessage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDefaultCondition", function() { return getDefaultCondition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAlertingValidationMessage", function() { return getAlertingValidationMessage; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
var _this = undefined;

var getDefaultCondition = function () { return ({
    type: 'query',
    query: { params: ['A', '5m', 'now'] },
    reducer: { type: 'avg', params: [] },
    evaluator: { type: 'gt', params: [null] },
    operator: { type: 'and' },
}); };
var getAlertingValidationMessage = function (transformations, targets, datasourceSrv, datasourceName) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
    var alertingNotSupported, templateVariablesNotSupported, targets_1, targets_1_1, target, dsName, ds, e_1_1;
    var e_1, _a;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
        switch (_b.label) {
            case 0:
                if (targets.length === 0) {
                    return [2 /*return*/, 'Could not find any metric queries'];
                }
                if (transformations && transformations.length) {
                    return [2 /*return*/, 'Transformations are not supported in alert queries'];
                }
                alertingNotSupported = 0;
                templateVariablesNotSupported = 0;
                _b.label = 1;
            case 1:
                _b.trys.push([1, 6, 7, 8]);
                targets_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](targets), targets_1_1 = targets_1.next();
                _b.label = 2;
            case 2:
                if (!!targets_1_1.done) return [3 /*break*/, 5];
                target = targets_1_1.value;
                dsName = target.datasource || datasourceName;
                return [4 /*yield*/, datasourceSrv.get(dsName)];
            case 3:
                ds = _b.sent();
                if (!ds.meta.alerting) {
                    alertingNotSupported++;
                }
                else if (ds.targetContainsTemplate && ds.targetContainsTemplate(target)) {
                    templateVariablesNotSupported++;
                }
                _b.label = 4;
            case 4:
                targets_1_1 = targets_1.next();
                return [3 /*break*/, 2];
            case 5: return [3 /*break*/, 8];
            case 6:
                e_1_1 = _b.sent();
                e_1 = { error: e_1_1 };
                return [3 /*break*/, 8];
            case 7:
                try {
                    if (targets_1_1 && !targets_1_1.done && (_a = targets_1.return)) _a.call(targets_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7 /*endfinally*/];
            case 8:
                if (alertingNotSupported === targets.length) {
                    return [2 /*return*/, 'The datasource does not support alerting queries'];
                }
                if (templateVariablesNotSupported === targets.length) {
                    return [2 /*return*/, 'Template variables are not supported in alert queries'];
                }
                return [2 /*return*/, ''];
        }
    });
}); };


/***/ }),

/***/ "./public/app/features/alerting/state/ThresholdMapper.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/alerting/state/ThresholdMapper.ts ***!
  \***************************************************************/
/*! exports provided: ThresholdMapper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThresholdMapper", function() { return ThresholdMapper; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

var ThresholdMapper = /** @class */ (function () {
    function ThresholdMapper() {
    }
    ThresholdMapper.alertToGraphThresholds = function (panel) {
        var e_1, _a;
        for (var i = 0; i < panel.alert.conditions.length; i++) {
            var condition = panel.alert.conditions[i];
            if (condition.type !== 'query') {
                continue;
            }
            var evaluator = condition.evaluator;
            var thresholds = (panel.thresholds = []);
            switch (evaluator.type) {
                case 'gt': {
                    var value = evaluator.params[0];
                    thresholds.push({ value: value, op: 'gt' });
                    break;
                }
                case 'lt': {
                    var value = evaluator.params[0];
                    thresholds.push({ value: value, op: 'lt' });
                    break;
                }
                case 'outside_range': {
                    var value1 = evaluator.params[0];
                    var value2 = evaluator.params[1];
                    if (value1 > value2) {
                        thresholds.push({ value: value1, op: 'gt' });
                        thresholds.push({ value: value2, op: 'lt' });
                    }
                    else {
                        thresholds.push({ value: value1, op: 'lt' });
                        thresholds.push({ value: value2, op: 'gt' });
                    }
                    break;
                }
                case 'within_range': {
                    var value1 = evaluator.params[0];
                    var value2 = evaluator.params[1];
                    if (value1 > value2) {
                        thresholds.push({ value: value1, op: 'lt' });
                        thresholds.push({ value: value2, op: 'gt' });
                    }
                    else {
                        thresholds.push({ value: value1, op: 'gt' });
                        thresholds.push({ value: value2, op: 'lt' });
                    }
                    break;
                }
            }
            break;
        }
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.thresholds), _c = _b.next(); !_c.done; _c = _b.next()) {
                var t = _c.value;
                t.fill = true;
                t.line = true;
                t.colorMode = 'critical';
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        var updated = true;
        return updated;
    };
    return ThresholdMapper;
}());



/***/ }),

/***/ "./public/app/features/alerting/state/actions.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/alerting/state/actions.ts ***!
  \*******************************************************/
/*! exports provided: ActionTypes, loadAlertRules, loadedAlertRules, setSearchQuery, getAlertRulesAsync, togglePauseAlertRule */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAlertRules", function() { return loadAlertRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadedAlertRules", function() { return loadedAlertRules; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSearchQuery", function() { return setSearchQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAlertRulesAsync", function() { return getAlertRulesAsync; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "togglePauseAlertRule", function() { return togglePauseAlertRule; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");


var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadAlertRules"] = "LOAD_ALERT_RULES";
    ActionTypes["LoadedAlertRules"] = "LOADED_ALERT_RULES";
    ActionTypes["SetSearchQuery"] = "SET_ALERT_SEARCH_QUERY";
})(ActionTypes || (ActionTypes = {}));
var loadAlertRules = function () { return ({
    type: ActionTypes.LoadAlertRules,
}); };
var loadedAlertRules = function (rules) { return ({
    type: ActionTypes.LoadedAlertRules,
    payload: rules,
}); };
var setSearchQuery = function (query) { return ({
    type: ActionTypes.SetSearchQuery,
    payload: query,
}); };
function getAlertRulesAsync(options) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var rules;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    dispatch(loadAlertRules());
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/alerts', options)];
                case 1:
                    rules = _a.sent();
                    dispatch(loadedAlertRules(rules));
                    return [2 /*return*/];
            }
        });
    }); };
}
function togglePauseAlertRule(id, options) {
    var _this = this;
    return function (dispatch, getState) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var stateFilter;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/alerts/" + id + "/pause", options)];
                case 1:
                    _a.sent();
                    stateFilter = getState().location.query.state || 'all';
                    dispatch(getAlertRulesAsync({ state: stateFilter.toString() }));
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/alerting/state/alertDef.ts":
/*!********************************************************!*\
  !*** ./public/app/features/alerting/state/alertDef.ts ***!
  \********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_components_query_part_query_part__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/components/query_part/query_part */ "./public/app/core/components/query_part/query_part.ts");


var alertQueryDef = new app_core_components_query_part_query_part__WEBPACK_IMPORTED_MODULE_1__["QueryPartDef"]({
    type: 'query',
    params: [
        { name: 'queryRefId', type: 'string', dynamicLookup: true },
        {
            name: 'from',
            type: 'string',
            options: ['10s', '1m', '5m', '10m', '15m', '1h', '24h', '48h'],
        },
        { name: 'to', type: 'string', options: ['now', 'now-1m', 'now-5m', 'now-10m', 'now-1h'] },
    ],
    defaultParams: ['#A', '15m', 'now', 'avg'],
});
var conditionTypes = [{ text: 'Query', value: 'query' }];
var alertStateSortScore = {
    alerting: 1,
    no_data: 2,
    pending: 3,
    ok: 4,
    paused: 5,
};
var evalFunctions = [
    { text: 'IS ABOVE', value: 'gt' },
    { text: 'IS BELOW', value: 'lt' },
    { text: 'IS OUTSIDE RANGE', value: 'outside_range' },
    { text: 'IS WITHIN RANGE', value: 'within_range' },
    { text: 'HAS NO VALUE', value: 'no_value' },
];
var evalOperators = [{ text: 'OR', value: 'or' }, { text: 'AND', value: 'and' }];
var reducerTypes = [
    { text: 'avg()', value: 'avg' },
    { text: 'min()', value: 'min' },
    { text: 'max()', value: 'max' },
    { text: 'sum()', value: 'sum' },
    { text: 'count()', value: 'count' },
    { text: 'last()', value: 'last' },
    { text: 'median()', value: 'median' },
    { text: 'diff()', value: 'diff' },
    { text: 'percent_diff()', value: 'percent_diff' },
    { text: 'count_non_null()', value: 'count_non_null' },
];
var noDataModes = [
    { text: 'Alerting', value: 'alerting' },
    { text: 'No Data', value: 'no_data' },
    { text: 'Keep Last State', value: 'keep_state' },
    { text: 'Ok', value: 'ok' },
];
var executionErrorModes = [{ text: 'Alerting', value: 'alerting' }, { text: 'Keep Last State', value: 'keep_state' }];
function createReducerPart(model) {
    var def = new app_core_components_query_part_query_part__WEBPACK_IMPORTED_MODULE_1__["QueryPartDef"]({ type: model.type, defaultParams: [] });
    return new app_core_components_query_part_query_part__WEBPACK_IMPORTED_MODULE_1__["QueryPart"](model, def);
}
function getStateDisplayModel(state) {
    switch (state) {
        case 'ok': {
            return {
                text: 'OK',
                iconClass: 'icon-gf icon-gf-online',
                stateClass: 'alert-state-ok',
            };
        }
        case 'alerting': {
            return {
                text: 'ALERTING',
                iconClass: 'icon-gf icon-gf-critical',
                stateClass: 'alert-state-critical',
            };
        }
        case 'no_data': {
            return {
                text: 'NO DATA',
                iconClass: 'fa fa-question',
                stateClass: 'alert-state-warning',
            };
        }
        case 'paused': {
            return {
                text: 'PAUSED',
                iconClass: 'fa fa-pause',
                stateClass: 'alert-state-paused',
            };
        }
        case 'pending': {
            return {
                text: 'PENDING',
                iconClass: 'fa fa-exclamation',
                stateClass: 'alert-state-warning',
            };
        }
        case 'unknown': {
            return {
                text: 'UNKNOWN',
                iconClass: 'fa fa-question',
                stateClass: 'alert-state-paused',
            };
        }
    }
    throw { message: 'Unknown alert state' };
}
function joinEvalMatches(matches, separator) {
    return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.reduce(matches, function (res, ev) {
        if (ev.metric !== undefined && ev.value !== undefined) {
            res.push(ev.metric + '=' + ev.value);
        }
        // For backwards compatibility . Should be be able to remove this after ~2017-06-01
        if (ev.Metric !== undefined && ev.Value !== undefined) {
            res.push(ev.Metric + '=' + ev.Value);
        }
        return res;
    }, []).join(separator);
}
function getAlertAnnotationInfo(ah) {
    // backward compatibility, can be removed in grafana 5.x
    // old way stored evalMatches in data property directly,
    // new way stores it in evalMatches property on new data object
    if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(ah.data)) {
        return joinEvalMatches(ah.data, ', ');
    }
    else if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(ah.data.evalMatches)) {
        return joinEvalMatches(ah.data.evalMatches, ', ');
    }
    if (ah.data.error) {
        return 'Error: ' + ah.data.error;
    }
    return '';
}
/* harmony default export */ __webpack_exports__["default"] = ({
    alertQueryDef: alertQueryDef,
    getStateDisplayModel: getStateDisplayModel,
    conditionTypes: conditionTypes,
    evalFunctions: evalFunctions,
    evalOperators: evalOperators,
    noDataModes: noDataModes,
    executionErrorModes: executionErrorModes,
    reducerTypes: reducerTypes,
    createReducerPart: createReducerPart,
    getAlertAnnotationInfo: getAlertAnnotationInfo,
    alertStateSortScore: alertStateSortScore,
});


/***/ }),

/***/ "./public/app/features/alerting/state/reducers.ts":
/*!********************************************************!*\
  !*** ./public/app/features/alerting/state/reducers.ts ***!
  \********************************************************/
/*! exports provided: initialState, alertRulesReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alertRulesReducer", function() { return alertRulesReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/alerting/state/actions.ts");
/* harmony import */ var _alertDef__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./alertDef */ "./public/app/features/alerting/state/alertDef.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




var initialState = { items: [], searchQuery: '', isLoading: false };
function convertToAlertRule(dto, state) {
    var stateModel = _alertDef__WEBPACK_IMPORTED_MODULE_2__["default"].getStateDisplayModel(state);
    var rule = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, dto, { stateText: stateModel.text, stateIcon: stateModel.iconClass, stateClass: stateModel.stateClass, stateAge: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(dto.newStateDate).fromNow(true) });
    if (rule.state !== 'paused') {
        if (rule.executionError) {
            rule.info = 'Execution Error: ' + rule.executionError;
        }
        if (rule.evalData && rule.evalData.noData) {
            rule.info = 'Query returned no data';
        }
    }
    return rule;
}
var alertRulesReducer = function (state, action) {
    if (state === void 0) { state = initialState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadAlertRules: {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { isLoading: true });
        }
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadedAlertRules: {
            var alertRules = action.payload;
            var alertRulesViewModel = alertRules.map(function (rule) {
                return convertToAlertRule(rule, rule.state);
            });
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { items: alertRulesViewModel, isLoading: false });
        }
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetSearchQuery:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchQuery: action.payload });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    alertRules: alertRulesReducer,
});


/***/ }),

/***/ "./public/app/features/all.ts":
/*!************************************!*\
  !*** ./public/app/features/all.ts ***!
  \************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _annotations_all__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./annotations/all */ "./public/app/features/annotations/all.ts");
/* harmony import */ var _templating_all__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./templating/all */ "./public/app/features/templating/all.ts");
/* harmony import */ var _plugins_all__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./plugins/all */ "./public/app/features/plugins/all.ts");
/* harmony import */ var _dashboard__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dashboard */ "./public/app/features/dashboard/index.ts");
/* harmony import */ var _playlist_all__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./playlist/all */ "./public/app/features/playlist/all.ts");
/* harmony import */ var _panel_all__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./panel/all */ "./public/app/features/panel/all.ts");
/* harmony import */ var _org_all__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./org/all */ "./public/app/features/org/all.ts");
/* harmony import */ var _admin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./admin */ "./public/app/features/admin/index.ts");
/* harmony import */ var _alerting_NotificationsEditCtrl__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./alerting/NotificationsEditCtrl */ "./public/app/features/alerting/NotificationsEditCtrl.ts");
/* harmony import */ var _alerting_NotificationsListCtrl__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./alerting/NotificationsListCtrl */ "./public/app/features/alerting/NotificationsListCtrl.ts");
/* harmony import */ var _manage_dashboards__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./manage-dashboards */ "./public/app/features/manage-dashboards/index.ts");
/* harmony import */ var _teams_CreateTeamCtrl__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./teams/CreateTeamCtrl */ "./public/app/features/teams/CreateTeamCtrl.ts");
/* harmony import */ var _profile_all__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./profile/all */ "./public/app/features/profile/all.ts");
/* harmony import */ var _datasources_settings_HttpSettingsCtrl__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./datasources/settings/HttpSettingsCtrl */ "./public/app/features/datasources/settings/HttpSettingsCtrl.ts");
/* harmony import */ var _datasources_settings_TlsAuthSettingsCtrl__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./datasources/settings/TlsAuthSettingsCtrl */ "./public/app/features/datasources/settings/TlsAuthSettingsCtrl.ts");

















/***/ }),

/***/ "./public/app/features/annotations/all.ts":
/*!************************************************!*\
  !*** ./public/app/features/annotations/all.ts ***!
  \************************************************/
/*! exports provided: AnnotationsSrv, eventEditor, EventManager, annotationTooltipDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _annotations_srv__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./annotations_srv */ "./public/app/features/annotations/annotations_srv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnnotationsSrv", function() { return _annotations_srv__WEBPACK_IMPORTED_MODULE_0__["AnnotationsSrv"]; });

/* harmony import */ var _event_editor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./event_editor */ "./public/app/features/annotations/event_editor.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "eventEditor", function() { return _event_editor__WEBPACK_IMPORTED_MODULE_1__["eventEditor"]; });

/* harmony import */ var _event_manager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./event_manager */ "./public/app/features/annotations/event_manager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventManager", function() { return _event_manager__WEBPACK_IMPORTED_MODULE_2__["EventManager"]; });

/* harmony import */ var _annotation_tooltip__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./annotation_tooltip */ "./public/app/features/annotations/annotation_tooltip.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "annotationTooltipDirective", function() { return _annotation_tooltip__WEBPACK_IMPORTED_MODULE_3__["annotationTooltipDirective"]; });








/***/ }),

/***/ "./public/app/features/annotations/annotation_tooltip.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/annotations/annotation_tooltip.ts ***!
  \***************************************************************/
/*! exports provided: annotationTooltipDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "annotationTooltipDirective", function() { return annotationTooltipDirective; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../alerting/state/alertDef */ "./public/app/features/alerting/state/alertDef.ts");




/** @ngInject */
function annotationTooltipDirective($sanitize, dashboardSrv, contextSrv, $compile) {
    function sanitizeString(str) {
        try {
            return $sanitize(str);
        }
        catch (err) {
            console.log('Could not sanitize annotation string, html escaping instead');
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(str);
        }
    }
    return {
        restrict: 'E',
        scope: {
            event: '=',
            onEdit: '&',
        },
        link: function (scope, element) {
            var event = scope.event;
            var title = event.title;
            var text = event.text;
            var dashboard = dashboardSrv.getCurrent();
            var tooltip = '<div class="graph-annotation">';
            var titleStateClass = '';
            if (event.alertId) {
                var stateModel = _alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_3__["default"].getStateDisplayModel(event.newState);
                titleStateClass = stateModel.stateClass;
                title = "<i class=\"" + stateModel.iconClass + "\"></i> " + stateModel.text;
                text = _alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_3__["default"].getAlertAnnotationInfo(event);
                if (event.text) {
                    text = text + '<br />' + event.text;
                }
            }
            else if (title) {
                text = title + '<br />' + (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(text) ? text : '');
                title = '';
            }
            var header = "<div class=\"graph-annotation__header\">";
            if (event.login) {
                header += "<div class=\"graph-annotation__user\" bs-tooltip=\"'Created by " + event.login + "'\"><img src=\"" + event.avatarUrl + "\" /></div>";
            }
            header += "\n          <span class=\"graph-annotation__title " + titleStateClass + "\">" + sanitizeString(title) + "</span>\n          <span class=\"graph-annotation__time\">" + dashboard.formatDate(event.min) + "</span>\n      ";
            // Show edit icon only for users with at least Editor role
            if (event.id && dashboard.meta.canEdit) {
                header += "\n          <span class=\"pointer graph-annotation__edit-icon\" ng-click=\"onEdit()\">\n            <i class=\"fa fa-pencil-square\"></i>\n          </span>\n        ";
            }
            header += "</div>";
            tooltip += header;
            tooltip += '<div class="graph-annotation__body">';
            if (text) {
                tooltip += '<div>' + sanitizeString(text.replace(/\n/g, '<br>')) + '</div>';
            }
            var tags = event.tags;
            if (tags && tags.length) {
                scope.tags = tags;
                tooltip +=
                    '<span class="label label-tag small" ng-repeat="tag in tags" tag-color-from-name="tag">{{tag}}</span><br/>';
            }
            tooltip += '</div>';
            tooltip += '</div>';
            var $tooltip = jquery__WEBPACK_IMPORTED_MODULE_1___default()(tooltip);
            $tooltip.appendTo(element);
            $compile(element.contents())(scope);
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('annotationTooltip', annotationTooltipDirective);


/***/ }),

/***/ "./public/app/features/annotations/annotations_srv.ts":
/*!************************************************************!*\
  !*** ./public/app/features/annotations/annotations_srv.ts ***!
  \************************************************************/
/*! exports provided: AnnotationsSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnnotationsSrv", function() { return AnnotationsSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _editor_ctrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./editor_ctrl */ "./public/app/features/annotations/editor_ctrl.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _events_processing__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./events_processing */ "./public/app/features/annotations/events_processing.ts");

// Libaries


// Components


// Utils & Services

var AnnotationsSrv = /** @class */ (function () {
    /** @ngInject */
    function AnnotationsSrv($rootScope, $q, datasourceSrv, backendSrv, timeSrv) {
        this.$rootScope = $rootScope;
        this.$q = $q;
        this.datasourceSrv = datasourceSrv;
        this.backendSrv = backendSrv;
        this.timeSrv = timeSrv;
    }
    AnnotationsSrv.prototype.init = function (dashboard) {
        // always clearPromiseCaches when loading new dashboard
        this.clearPromiseCaches();
        // clear promises on refresh events
        dashboard.on('refresh', this.clearPromiseCaches.bind(this));
    };
    AnnotationsSrv.prototype.clearPromiseCaches = function () {
        this.globalAnnotationsPromise = null;
        this.alertStatesPromise = null;
        this.datasourcePromises = null;
    };
    AnnotationsSrv.prototype.getAnnotations = function (options) {
        var _this = this;
        return this.$q
            .all([this.getGlobalAnnotations(options), this.getAlertStates(options)])
            .then(function (results) {
            // combine the annotations and flatten results
            var annotations = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.flattenDeep(results[0]);
            // filter out annotations that do not belong to requesting panel
            annotations = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.filter(annotations, function (item) {
                // if event has panel id and query is of type dashboard then panel and requesting panel id must match
                if (item.panelId && item.source.type === 'dashboard') {
                    return item.panelId === options.panel.id;
                }
                return true;
            });
            annotations = Object(_events_processing__WEBPACK_IMPORTED_MODULE_5__["dedupAnnotations"])(annotations);
            // look for alert state for this panel
            var alertState = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(results[1], { panelId: options.panel.id });
            return {
                annotations: annotations,
                alertState: alertState,
            };
        })
            .catch(function (err) {
            if (!err.message && err.data && err.data.message) {
                err.message = err.data.message;
            }
            console.log('AnnotationSrv.query error', err);
            _this.$rootScope.appEvent('alert-error', ['Annotation Query Failed', err.message || err]);
            return [];
        });
    };
    AnnotationsSrv.prototype.getAlertStates = function (options) {
        if (!options.dashboard.id) {
            return this.$q.when([]);
        }
        // ignore if no alerts
        if (options.panel && !options.panel.alert) {
            return this.$q.when([]);
        }
        if (options.range.raw.to !== 'now') {
            return this.$q.when([]);
        }
        if (this.alertStatesPromise) {
            return this.alertStatesPromise;
        }
        this.alertStatesPromise = this.backendSrv.get('/api/alerts/states-for-dashboard', {
            dashboardId: options.dashboard.id,
        });
        return this.alertStatesPromise;
    };
    AnnotationsSrv.prototype.getGlobalAnnotations = function (options) {
        var e_1, _a;
        var _this = this;
        var dashboard = options.dashboard;
        if (this.globalAnnotationsPromise) {
            return this.globalAnnotationsPromise;
        }
        var range = this.timeSrv.timeRange();
        var promises = [];
        var dsPromises = [];
        var _loop_1 = function (annotation) {
            if (!annotation.enable) {
                return "continue";
            }
            if (annotation.snapshotData) {
                return { value: this_1.translateQueryResult(annotation, annotation.snapshotData) };
            }
            var datasourcePromise = this_1.datasourceSrv.get(annotation.datasource);
            dsPromises.push(datasourcePromise);
            promises.push(datasourcePromise
                .then(function (datasource) {
                // issue query against data source
                return datasource.annotationQuery({
                    range: range,
                    rangeRaw: range.raw,
                    annotation: annotation,
                    dashboard: dashboard,
                });
            })
                .then(function (results) {
                // store response in annotation object if this is a snapshot call
                if (dashboard.snapshot) {
                    annotation.snapshotData = angular__WEBPACK_IMPORTED_MODULE_1___default.a.copy(results);
                }
                // translate result
                return _this.translateQueryResult(annotation, results);
            }));
        };
        var this_1 = this;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboard.annotations.list), _c = _b.next(); !_c.done; _c = _b.next()) {
                var annotation = _c.value;
                var state_1 = _loop_1(annotation);
                if (typeof state_1 === "object")
                    return state_1.value;
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        this.datasourcePromises = this.$q.all(dsPromises);
        this.globalAnnotationsPromise = this.$q.all(promises);
        return this.globalAnnotationsPromise;
    };
    AnnotationsSrv.prototype.saveAnnotationEvent = function (annotation) {
        this.globalAnnotationsPromise = null;
        return this.backendSrv.post('/api/annotations', annotation);
    };
    AnnotationsSrv.prototype.updateAnnotationEvent = function (annotation) {
        this.globalAnnotationsPromise = null;
        return this.backendSrv.put("/api/annotations/" + annotation.id, annotation);
    };
    AnnotationsSrv.prototype.deleteAnnotationEvent = function (annotation) {
        this.globalAnnotationsPromise = null;
        var deleteUrl = "/api/annotations/" + annotation.id;
        return this.backendSrv.delete(deleteUrl);
    };
    AnnotationsSrv.prototype.translateQueryResult = function (annotation, results) {
        var e_2, _a;
        // if annotation has snapshotData
        // make clone and remove it
        if (annotation.snapshotData) {
            annotation = angular__WEBPACK_IMPORTED_MODULE_1___default.a.copy(annotation);
            delete annotation.snapshotData;
        }
        try {
            for (var results_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](results), results_1_1 = results_1.next(); !results_1_1.done; results_1_1 = results_1.next()) {
                var item = results_1_1.value;
                item.source = annotation;
                item.isRegion = item.timeEnd && item.time !== item.timeEnd;
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (results_1_1 && !results_1_1.done && (_a = results_1.return)) _a.call(results_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return results;
    };
    return AnnotationsSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_4__["default"].service('annotationsSrv', AnnotationsSrv);


/***/ }),

/***/ "./public/app/features/annotations/editor_ctrl.ts":
/*!********************************************************!*\
  !*** ./public/app/features/annotations/editor_ctrl.ts ***!
  \********************************************************/
/*! exports provided: AnnotationsEditorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnnotationsEditorCtrl", function() { return AnnotationsEditorCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");






var AnnotationsEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function AnnotationsEditorCtrl($scope, datasourceSrv) {
        var _this = this;
        this.$scope = $scope;
        this.datasourceSrv = datasourceSrv;
        this.annotationDefaults = {
            name: '',
            datasource: null,
            iconColor: 'rgba(255, 96, 96, 1)',
            enable: true,
            showIn: 0,
            hide: false,
        };
        this.emptyListCta = {
            title: 'There are no custom annotation queries added yet',
            buttonIcon: 'gicon gicon-annotation',
            buttonTitle: 'Add Annotation Query',
            infoBox: {
                __html: "<p>Annotations provide a way to integrate event data into your graphs. They are visualized as vertical lines\n    and icons on all graph panels. When you hover over an annotation icon you can get event text &amp; tags for\n    the event. You can add annotation events directly from grafana by holding CTRL or CMD + click on graph (or\n    drag region). These will be stored in Grafana's annotation database.\n  </p>\n  Checkout the\n  <a class='external-link' target='_blank' href='http://docs.grafana.org/reference/annotations/'\n    >Annotations documentation</a\n  >\n  for more information.",
            },
            infoBoxTitle: 'What are annotations?',
        };
        this.showOptions = [{ text: 'All Panels', value: 0 }, { text: 'Specific Panels', value: 1 }];
        this.setupNew = function () {
            _this.mode = 'new';
            _this.reset();
        };
        $scope.ctrl = this;
        this.dashboard = $scope.dashboard;
        this.mode = 'list';
        this.datasources = datasourceSrv.getAnnotationSources();
        this.annotations = this.dashboard.annotations.list;
        this.reset();
        this.onColorChange = this.onColorChange.bind(this);
    }
    AnnotationsEditorCtrl.prototype.datasourceChanged = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var newDatasource;
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.datasourceSrv.get(this.currentAnnotation.datasource)];
                    case 1:
                        newDatasource = _a.sent();
                        this.$scope.$apply(function () {
                            _this.currentDatasource = newDatasource;
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    AnnotationsEditorCtrl.prototype.edit = function (annotation) {
        this.currentAnnotation = annotation;
        this.currentAnnotation.showIn = this.currentAnnotation.showIn || 0;
        this.currentIsNew = false;
        this.datasourceChanged();
        this.mode = 'edit';
        jquery__WEBPACK_IMPORTED_MODULE_3___default()('.tooltip.in').remove();
    };
    AnnotationsEditorCtrl.prototype.reset = function () {
        this.currentAnnotation = angular__WEBPACK_IMPORTED_MODULE_1___default.a.copy(this.annotationDefaults);
        this.currentAnnotation.datasource = this.datasources[0].name;
        this.currentIsNew = true;
        this.datasourceChanged();
    };
    AnnotationsEditorCtrl.prototype.update = function () {
        this.reset();
        this.mode = 'list';
    };
    AnnotationsEditorCtrl.prototype.backToList = function () {
        this.mode = 'list';
    };
    AnnotationsEditorCtrl.prototype.move = function (index, dir) {
        // @ts-ignore
        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.move(this.annotations, index, index + dir);
    };
    AnnotationsEditorCtrl.prototype.add = function () {
        var sameName = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(this.annotations, { name: this.currentAnnotation.name });
        if (sameName) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_5__["default"].emit('alert-warning', ['Validation', 'Annotations with the same name already exists']);
            return;
        }
        this.annotations.push(this.currentAnnotation);
        this.reset();
        this.mode = 'list';
        this.dashboard.updateSubmenuVisibility();
    };
    AnnotationsEditorCtrl.prototype.removeAnnotation = function (annotation) {
        var index = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.indexOf(this.annotations, annotation);
        this.annotations.splice(index, 1);
        this.dashboard.updateSubmenuVisibility();
    };
    AnnotationsEditorCtrl.prototype.onColorChange = function (newColor) {
        this.currentAnnotation.iconColor = newColor;
    };
    return AnnotationsEditorCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_4__["default"].controller('AnnotationsEditorCtrl', AnnotationsEditorCtrl);


/***/ }),

/***/ "./public/app/features/annotations/event_editor.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/annotations/event_editor.ts ***!
  \*********************************************************/
/*! exports provided: EventEditorCtrl, eventEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventEditorCtrl", function() { return EventEditorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eventEditor", function() { return eventEditor; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");



var EventEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function EventEditorCtrl(annotationsSrv) {
        this.annotationsSrv = annotationsSrv;
        this.event.panelId = this.panelCtrl.panel.id;
        this.event.dashboardId = this.panelCtrl.dashboard.id;
        // Annotations query returns time as Unix timestamp in milliseconds
        this.event.time = tryEpochToMoment(this.event.time);
        if (this.event.isRegion) {
            this.event.timeEnd = tryEpochToMoment(this.event.timeEnd);
        }
        this.timeFormated = this.panelCtrl.dashboard.formatDate(this.event.time);
    }
    EventEditorCtrl.prototype.save = function () {
        var _this = this;
        if (!this.form.$valid) {
            return;
        }
        var saveModel = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.cloneDeep(this.event);
        saveModel.time = saveModel.time.valueOf();
        saveModel.timeEnd = 0;
        if (saveModel.isRegion) {
            saveModel.timeEnd = this.event.timeEnd.valueOf();
            if (saveModel.timeEnd < saveModel.time) {
                console.log('invalid time');
                return;
            }
        }
        if (saveModel.id) {
            this.annotationsSrv
                .updateAnnotationEvent(saveModel)
                .then(function () {
                _this.panelCtrl.refresh();
                _this.close();
            })
                .catch(function () {
                _this.panelCtrl.refresh();
                _this.close();
            });
        }
        else {
            this.annotationsSrv
                .saveAnnotationEvent(saveModel)
                .then(function () {
                _this.panelCtrl.refresh();
                _this.close();
            })
                .catch(function () {
                _this.panelCtrl.refresh();
                _this.close();
            });
        }
    };
    EventEditorCtrl.prototype.delete = function () {
        var _this = this;
        return this.annotationsSrv
            .deleteAnnotationEvent(this.event)
            .then(function () {
            _this.panelCtrl.refresh();
            _this.close();
        })
            .catch(function () {
            _this.panelCtrl.refresh();
            _this.close();
        });
    };
    return EventEditorCtrl;
}());

function tryEpochToMoment(timestamp) {
    if (timestamp && lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(timestamp)) {
        var epoch = Number(timestamp);
        return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(epoch);
    }
    else {
        return timestamp;
    }
}
function eventEditor() {
    return {
        restrict: 'E',
        controller: EventEditorCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        templateUrl: 'public/app/features/annotations/partials/event_editor.html',
        scope: {
            panelCtrl: '=',
            event: '=',
            close: '&',
        },
    };
}
app_core_core__WEBPACK_IMPORTED_MODULE_1__["coreModule"].directive('eventEditor', eventEditor);


/***/ }),

/***/ "./public/app/features/annotations/event_manager.ts":
/*!**********************************************************!*\
  !*** ./public/app/features/annotations/event_manager.ts ***!
  \**********************************************************/
/*! exports provided: EventManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventManager", function() { return EventManager; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");



var EventManager = /** @class */ (function () {
    function EventManager(panelCtrl) {
        this.panelCtrl = panelCtrl;
    }
    EventManager.prototype.editorClosed = function () {
        this.event = null;
        this.editorOpen = false;
        this.panelCtrl.render();
    };
    EventManager.prototype.editorOpened = function () {
        this.editorOpen = true;
    };
    EventManager.prototype.updateTime = function (range) {
        if (!this.event) {
            this.event = {};
            this.event.dashboardId = this.panelCtrl.dashboard.id;
            this.event.panelId = this.panelCtrl.panel.id;
        }
        // update time
        this.event.time = range.from;
        this.event.isRegion = false;
        if (range.to) {
            this.event.timeEnd = range.to;
            this.event.isRegion = true;
        }
        this.panelCtrl.render();
    };
    EventManager.prototype.editEvent = function (event, elem) {
        this.event = event;
        this.panelCtrl.render();
    };
    EventManager.prototype.addFlotEvents = function (annotations, flotOptions) {
        if (!this.event && annotations.length === 0) {
            return;
        }
        var types = {
            $__alerting: {
                color: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ALERTING_COLOR"],
                position: 'BOTTOM',
                markerSize: 5,
            },
            $__ok: {
                color: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["OK_COLOR"],
                position: 'BOTTOM',
                markerSize: 5,
            },
            $__no_data: {
                color: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["NO_DATA_COLOR"],
                position: 'BOTTOM',
                markerSize: 5,
            },
            $__pending: {
                color: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PENDING_COLOR"],
                position: 'BOTTOM',
                markerSize: 5,
            },
            $__editing: {
                color: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DEFAULT_ANNOTATION_COLOR"],
                position: 'BOTTOM',
                markerSize: 5,
            },
        };
        if (this.event) {
            if (this.event.isRegion) {
                annotations = [
                    {
                        isRegion: true,
                        min: this.event.time,
                        timeEnd: this.event.timeEnd,
                        text: this.event.text,
                        eventType: '$__editing',
                        editModel: this.event,
                    },
                ];
            }
            else {
                annotations = [
                    {
                        min: this.event.time,
                        text: this.event.text,
                        editModel: this.event,
                        eventType: '$__editing',
                    },
                ];
            }
        }
        else {
            // annotations from query
            for (var i = 0; i < annotations.length; i++) {
                var item = annotations[i];
                // add properties used by jquery flot events
                item.min = item.time;
                item.max = item.time;
                item.eventType = item.source.name;
                if (item.newState) {
                    item.eventType = '$__' + item.newState;
                    continue;
                }
                if (!types[item.source.name]) {
                    types[item.source.name] = {
                        color: item.source.iconColor,
                        position: 'BOTTOM',
                        markerSize: 5,
                    };
                }
            }
        }
        var regions = getRegions(annotations);
        addRegionMarking(regions, flotOptions);
        var eventSectionHeight = 20;
        var eventSectionMargin = 7;
        flotOptions.grid.eventSectionHeight = eventSectionMargin;
        flotOptions.xaxis.eventSectionHeight = eventSectionHeight;
        flotOptions.events = {
            levels: lodash__WEBPACK_IMPORTED_MODULE_0___default.a.keys(types).length + 1,
            data: annotations,
            types: types,
            manager: this,
        };
    };
    return EventManager;
}());

function getRegions(events) {
    return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.filter(events, 'isRegion');
}
function addRegionMarking(regions, flotOptions) {
    var markings = flotOptions.grid.markings;
    var defaultColor = _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DEFAULT_ANNOTATION_COLOR"];
    var fillColor;
    lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(regions, function (region) {
        if (region.source) {
            fillColor = region.source.iconColor || defaultColor;
        }
        else {
            fillColor = defaultColor;
        }
        fillColor = addAlphaToRGB(fillColor, _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["REGION_FILL_ALPHA"]);
        markings.push({
            xaxis: { from: region.min, to: region.timeEnd },
            color: fillColor,
        });
    });
}
function addAlphaToRGB(colorString, alpha) {
    var color = tinycolor2__WEBPACK_IMPORTED_MODULE_1___default()(colorString);
    if (color.isValid()) {
        color.setAlpha(alpha);
        return color.toRgbString();
    }
    else {
        return colorString;
    }
}


/***/ }),

/***/ "./public/app/features/annotations/events_processing.ts":
/*!**************************************************************!*\
  !*** ./public/app/features/annotations/events_processing.ts ***!
  \**************************************************************/
/*! exports provided: dedupAnnotations */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dedupAnnotations", function() { return dedupAnnotations; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

function dedupAnnotations(annotations) {
    var dedup = [];
    // Split events by annotationId property existence
    var events = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.partition(annotations, 'id');
    var eventsById = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.groupBy(events[0], 'id');
    dedup = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(eventsById, function (eventGroup) {
        if (eventGroup.length > 1 && !lodash__WEBPACK_IMPORTED_MODULE_0___default.a.every(eventGroup, isPanelAlert)) {
            // Get first non-panel alert
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(eventGroup, function (event) {
                return event.eventType !== 'panel-alert';
            });
        }
        else {
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.head(eventGroup);
        }
    });
    dedup = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.concat(dedup, events[1]);
    return dedup;
}
function isPanelAlert(event) {
    return event.eventType === 'panel-alert';
}


/***/ }),

/***/ "./public/app/features/api-keys/state/actions.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/api-keys/state/actions.ts ***!
  \*******************************************************/
/*! exports provided: ActionTypes, addApiKey, loadApiKeys, deleteApiKey, setSearchQuery */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addApiKey", function() { return addApiKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadApiKeys", function() { return loadApiKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteApiKey", function() { return deleteApiKey; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSearchQuery", function() { return setSearchQuery; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");


var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadApiKeys"] = "LOAD_API_KEYS";
    ActionTypes["SetApiKeysSearchQuery"] = "SET_API_KEYS_SEARCH_QUERY";
})(ActionTypes || (ActionTypes = {}));
var apiKeysLoaded = function (apiKeys) { return ({
    type: ActionTypes.LoadApiKeys,
    payload: apiKeys,
}); };
function addApiKey(apiKey, openModal) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var result;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post('/api/auth/keys', apiKey)];
                case 1:
                    result = _a.sent();
                    dispatch(setSearchQuery(''));
                    dispatch(loadApiKeys());
                    openModal(result.key);
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadApiKeys() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/auth/keys')];
                case 1:
                    response = _a.sent();
                    dispatch(apiKeysLoaded(response));
                    return [2 /*return*/];
            }
        });
    }); };
}
function deleteApiKey(id) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])()
                .delete('/api/auth/keys/' + id)
                .then(dispatch(loadApiKeys()));
            return [2 /*return*/];
        });
    }); };
}
var setSearchQuery = function (searchQuery) { return ({
    type: ActionTypes.SetApiKeysSearchQuery,
    payload: searchQuery,
}); };


/***/ }),

/***/ "./public/app/features/api-keys/state/reducers.ts":
/*!********************************************************!*\
  !*** ./public/app/features/api-keys/state/reducers.ts ***!
  \********************************************************/
/*! exports provided: initialApiKeysState, apiKeysReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialApiKeysState", function() { return initialApiKeysState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "apiKeysReducer", function() { return apiKeysReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/api-keys/state/actions.ts");


var initialApiKeysState = {
    keys: [],
    searchQuery: '',
    hasFetched: false,
};
var apiKeysReducer = function (state, action) {
    if (state === void 0) { state = initialApiKeysState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadApiKeys:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hasFetched: true, keys: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetApiKeysSearchQuery:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchQuery: action.payload });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    apiKeys: apiKeysReducer,
});


/***/ }),

/***/ "./public/app/features/dashboard/components/AdHocFilters/AdHocFiltersCtrl.ts":
/*!***********************************************************************************!*\
  !*** ./public/app/features/dashboard/components/AdHocFilters/AdHocFiltersCtrl.ts ***!
  \***********************************************************************************/
/*! exports provided: AdHocFiltersCtrl, adHocFiltersComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdHocFiltersCtrl", function() { return AdHocFiltersCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adHocFiltersComponent", function() { return adHocFiltersComponent; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");




var AdHocFiltersCtrl = /** @class */ (function () {
    /** @ngInject */
    function AdHocFiltersCtrl(uiSegmentSrv, datasourceSrv, $q, variableSrv, $scope) {
        this.uiSegmentSrv = uiSegmentSrv;
        this.datasourceSrv = datasourceSrv;
        this.$q = $q;
        this.variableSrv = variableSrv;
        this.removeTagFilterSegment = uiSegmentSrv.newSegment({
            fake: true,
            value: '-- remove filter --',
        });
        this.buildSegmentModel();
        this.dashboard.events.on('template-variable-value-updated', this.buildSegmentModel.bind(this), $scope);
    }
    AdHocFiltersCtrl.prototype.buildSegmentModel = function () {
        var e_1, _a;
        this.segments = [];
        if (this.variable.value && !lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(this.variable.value)) {
        }
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.variable.filters), _c = _b.next(); !_c.done; _c = _b.next()) {
                var tag = _c.value;
                if (this.segments.length > 0) {
                    this.segments.push(this.uiSegmentSrv.newCondition('AND'));
                }
                if (tag.key !== undefined && tag.value !== undefined) {
                    this.segments.push(this.uiSegmentSrv.newKey(tag.key));
                    this.segments.push(this.uiSegmentSrv.newOperator(tag.operator));
                    this.segments.push(this.uiSegmentSrv.newKeyValue(tag.value));
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        this.segments.push(this.uiSegmentSrv.newPlusButton());
    };
    AdHocFiltersCtrl.prototype.getOptions = function (segment, index) {
        var _this = this;
        if (segment.type === 'operator') {
            return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~']));
        }
        if (segment.type === 'condition') {
            return this.$q.when([this.uiSegmentSrv.newSegment('AND')]);
        }
        return this.datasourceSrv.get(this.variable.datasource).then(function (ds) {
            var options = {};
            var promise = null;
            if (segment.type !== 'value') {
                promise = ds.getTagKeys ? ds.getTagKeys() : Promise.resolve([]);
            }
            else {
                options.key = _this.segments[index - 2].value;
                promise = ds.getTagValues ? ds.getTagValues(options) : Promise.resolve([]);
            }
            return promise.then(function (results) {
                results = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(results, function (segment) {
                    return _this.uiSegmentSrv.newSegment({ value: segment.text });
                });
                // add remove option for keys
                if (segment.type === 'key') {
                    results.splice(0, 0, angular__WEBPACK_IMPORTED_MODULE_2___default.a.copy(_this.removeTagFilterSegment));
                }
                return results;
            });
        });
    };
    AdHocFiltersCtrl.prototype.segmentChanged = function (segment, index) {
        this.segments[index] = segment;
        // handle remove tag condition
        if (segment.value === this.removeTagFilterSegment.value) {
            this.segments.splice(index, 3);
            if (this.segments.length === 0) {
                this.segments.push(this.uiSegmentSrv.newPlusButton());
            }
            else if (this.segments.length > 2) {
                this.segments.splice(Math.max(index - 1, 0), 1);
                if (this.segments[this.segments.length - 1].type !== 'plus-button') {
                    this.segments.push(this.uiSegmentSrv.newPlusButton());
                }
            }
        }
        else {
            if (segment.type === 'plus-button') {
                if (index > 2) {
                    this.segments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
                }
                this.segments.push(this.uiSegmentSrv.newOperator('='));
                this.segments.push(this.uiSegmentSrv.newFake('select value', 'value', 'query-segment-value'));
                segment.type = 'key';
                segment.cssClass = 'query-segment-key';
            }
            if (index + 1 === this.segments.length) {
                this.segments.push(this.uiSegmentSrv.newPlusButton());
            }
        }
        this.updateVariableModel();
    };
    AdHocFiltersCtrl.prototype.updateVariableModel = function () {
        var filters = [];
        var filterIndex = -1;
        var hasFakes = false;
        this.segments.forEach(function (segment) {
            if (segment.type === 'value' && segment.fake) {
                hasFakes = true;
                return;
            }
            switch (segment.type) {
                case 'key': {
                    filters.push({ key: segment.value });
                    filterIndex += 1;
                    break;
                }
                case 'value': {
                    filters[filterIndex].value = segment.value;
                    break;
                }
                case 'operator': {
                    filters[filterIndex].operator = segment.value;
                    break;
                }
                case 'condition': {
                    filters[filterIndex].condition = segment.value;
                    break;
                }
            }
        });
        if (hasFakes) {
            return;
        }
        this.variable.setFilters(filters);
        this.variableSrv.variableUpdated(this.variable, true);
    };
    return AdHocFiltersCtrl;
}());

var template = "\n<div class=\"gf-form-inline\">\n  <div class=\"gf-form\" ng-repeat=\"segment in ctrl.segments\">\n    <metric-segment segment=\"segment\" get-options=\"ctrl.getOptions(segment, $index)\"\n                    on-change=\"ctrl.segmentChanged(segment, $index)\"></metric-segment>\n  </div>\n</div>\n";
function adHocFiltersComponent() {
    return {
        restrict: 'E',
        template: template,
        controller: AdHocFiltersCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            variable: '=',
            dashboard: '=',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_3__["default"].directive('adHocFilters', adHocFiltersComponent);


/***/ }),

/***/ "./public/app/features/dashboard/components/AdHocFilters/index.ts":
/*!************************************************************************!*\
  !*** ./public/app/features/dashboard/components/AdHocFilters/index.ts ***!
  \************************************************************************/
/*! exports provided: AdHocFiltersCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AdHocFiltersCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AdHocFiltersCtrl */ "./public/app/features/dashboard/components/AdHocFilters/AdHocFiltersCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdHocFiltersCtrl", function() { return _AdHocFiltersCtrl__WEBPACK_IMPORTED_MODULE_0__["AdHocFiltersCtrl"]; });




/***/ }),

/***/ "./public/app/features/dashboard/components/DashExportModal/DashExportCtrl.ts":
/*!************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashExportModal/DashExportCtrl.ts ***!
  \************************************************************************************/
/*! exports provided: DashExportCtrl, dashExportDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashExportCtrl", function() { return DashExportCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashExportDirective", function() { return dashExportDirective; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! file-saver */ "./node_modules/file-saver/FileSaver.js");
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _DashboardExporter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DashboardExporter */ "./public/app/features/dashboard/components/DashExportModal/DashboardExporter.ts");




var DashExportCtrl = /** @class */ (function () {
    /** @ngInject */
    function DashExportCtrl(dashboardSrv, datasourceSrv, $scope, $rootScope) {
        this.dashboardSrv = dashboardSrv;
        this.$scope = $scope;
        this.$rootScope = $rootScope;
        this.exporter = new _DashboardExporter__WEBPACK_IMPORTED_MODULE_3__["DashboardExporter"](datasourceSrv);
        this.dash = this.dashboardSrv.getCurrent();
    }
    DashExportCtrl.prototype.saveDashboardAsFile = function () {
        var _this = this;
        if (this.shareExternally) {
            this.exporter.makeExportable(this.dash).then(function (dashboardJson) {
                _this.$scope.$apply(function () {
                    _this.openSaveAsDialog(dashboardJson);
                });
            });
        }
        else {
            this.openSaveAsDialog(this.dash.getSaveModelClone());
        }
    };
    DashExportCtrl.prototype.viewJson = function () {
        var _this = this;
        if (this.shareExternally) {
            this.exporter.makeExportable(this.dash).then(function (dashboardJson) {
                _this.$scope.$apply(function () {
                    _this.openJsonModal(dashboardJson);
                });
            });
        }
        else {
            this.openJsonModal(this.dash.getSaveModelClone());
        }
    };
    DashExportCtrl.prototype.openSaveAsDialog = function (dash) {
        var blob = new Blob([angular__WEBPACK_IMPORTED_MODULE_0___default.a.toJson(dash, true)], {
            type: 'application/json;charset=utf-8',
        });
        Object(file_saver__WEBPACK_IMPORTED_MODULE_1__["saveAs"])(blob, dash.title + '-' + new Date().getTime() + '.json');
    };
    DashExportCtrl.prototype.openJsonModal = function (clone) {
        var model = {
            object: clone,
            enableCopy: true,
        };
        this.$rootScope.appEvent('show-modal', {
            src: 'public/app/partials/edit_json.html',
            model: model,
        });
        this.dismiss();
    };
    return DashExportCtrl;
}());

function dashExportDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/DashExportModal/template.html',
        controller: DashExportCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: { dismiss: '&' },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('dashExportModal', dashExportDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/DashExportModal/DashboardExporter.ts":
/*!***************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashExportModal/DashboardExporter.ts ***!
  \***************************************************************************************/
/*! exports provided: DashboardExporter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardExporter", function() { return DashboardExporter; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



var DashboardExporter = /** @class */ (function () {
    function DashboardExporter(datasourceSrv) {
        this.datasourceSrv = datasourceSrv;
    }
    DashboardExporter.prototype.makeExportable = function (dashboard) {
        var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e;
        var _this = this;
        // clean up repeated rows and panels,
        // this is done on the live real dashboard instance, not on a clone
        // so we need to undo this
        // this is pretty hacky and needs to be changed
        dashboard.cleanUpRepeats();
        var saveModel = dashboard.getSaveModelClone();
        saveModel.id = null;
        // undo repeat cleanup
        dashboard.processRepeats();
        var inputs = [];
        var requires = {};
        var datasources = {};
        var promises = [];
        var variableLookup = {};
        try {
            for (var _f = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](saveModel.templating.list), _g = _f.next(); !_g.done; _g = _f.next()) {
                var variable = _g.value;
                variableLookup[variable.name] = variable;
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
            }
            finally { if (e_1) throw e_1.error; }
        }
        var templateizeDatasourceUsage = function (obj) {
            var datasource = obj.datasource;
            var datasourceVariable = null;
            // ignore data source properties that contain a variable
            if (datasource && datasource.indexOf('$') === 0) {
                datasourceVariable = variableLookup[datasource.substring(1)];
                if (datasourceVariable && datasourceVariable.current) {
                    datasource = datasourceVariable.current.value;
                }
            }
            promises.push(_this.datasourceSrv.get(datasource).then(function (ds) {
                if (ds.meta.builtIn) {
                    return;
                }
                // add data source type to require list
                requires['datasource' + ds.meta.id] = {
                    type: 'datasource',
                    id: ds.meta.id,
                    name: ds.meta.name,
                    version: ds.meta.info.version || '1.0.0',
                };
                // if used via variable we can skip templatizing usage
                if (datasourceVariable) {
                    return;
                }
                var refName = 'DS_' + ds.name.replace(' ', '_').toUpperCase();
                datasources[refName] = {
                    name: refName,
                    label: ds.name,
                    description: '',
                    type: 'datasource',
                    pluginId: ds.meta.id,
                    pluginName: ds.meta.name,
                };
                obj.datasource = '${' + refName + '}';
            }));
        };
        var processPanel = function (panel) {
            var e_6, _a;
            if (panel.datasource !== undefined) {
                templateizeDatasourceUsage(panel);
            }
            if (panel.targets) {
                try {
                    for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.targets), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var target = _c.value;
                        if (target.datasource !== undefined) {
                            templateizeDatasourceUsage(target);
                        }
                    }
                }
                catch (e_6_1) { e_6 = { error: e_6_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_6) throw e_6.error; }
                }
            }
            var panelDef = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].panels[panel.type];
            if (panelDef) {
                requires['panel' + panelDef.id] = {
                    type: 'panel',
                    id: panelDef.id,
                    name: panelDef.name,
                    version: panelDef.info.version,
                };
            }
        };
        try {
            // check up panel data sources
            for (var _h = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](saveModel.panels), _j = _h.next(); !_j.done; _j = _h.next()) {
                var panel = _j.value;
                processPanel(panel);
                // handle collapsed rows
                if (panel.collapsed !== undefined && panel.collapsed === true && panel.panels) {
                    try {
                        for (var _k = (e_3 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.panels)), _l = _k.next(); !_l.done; _l = _k.next()) {
                            var rowPanel = _l.value;
                            processPanel(rowPanel);
                        }
                    }
                    catch (e_3_1) { e_3 = { error: e_3_1 }; }
                    finally {
                        try {
                            if (_l && !_l.done && (_c = _k.return)) _c.call(_k);
                        }
                        finally { if (e_3) throw e_3.error; }
                    }
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_j && !_j.done && (_b = _h.return)) _b.call(_h);
            }
            finally { if (e_2) throw e_2.error; }
        }
        try {
            // templatize template vars
            for (var _m = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](saveModel.templating.list), _o = _m.next(); !_o.done; _o = _m.next()) {
                var variable = _o.value;
                if (variable.type === 'query') {
                    templateizeDatasourceUsage(variable);
                    variable.options = [];
                    variable.current = {};
                    variable.refresh = variable.refresh > 0 ? variable.refresh : 1;
                }
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_o && !_o.done && (_d = _m.return)) _d.call(_m);
            }
            finally { if (e_4) throw e_4.error; }
        }
        try {
            // templatize annotations vars
            for (var _p = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](saveModel.annotations.list), _q = _p.next(); !_q.done; _q = _p.next()) {
                var annotationDef = _q.value;
                templateizeDatasourceUsage(annotationDef);
            }
        }
        catch (e_5_1) { e_5 = { error: e_5_1 }; }
        finally {
            try {
                if (_q && !_q.done && (_e = _p.return)) _e.call(_p);
            }
            finally { if (e_5) throw e_5.error; }
        }
        // add grafana version
        requires['grafana'] = {
            type: 'grafana',
            id: 'grafana',
            name: 'Grafana',
            version: app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].buildInfo.version,
        };
        return Promise.all(promises)
            .then(function () {
            var e_7, _a;
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(datasources, function (value) {
                inputs.push(value);
            });
            try {
                // templatize constants
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](saveModel.templating.list), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.type === 'constant') {
                        var refName = 'VAR_' + variable.name.replace(' ', '_').toUpperCase();
                        inputs.push({
                            name: refName,
                            type: 'constant',
                            label: variable.label || variable.name,
                            value: variable.current.value,
                            description: '',
                        });
                        // update current and option
                        variable.query = '${' + refName + '}';
                        variable.options[0] = variable.current = {
                            value: variable.query,
                            text: variable.query,
                        };
                    }
                }
            }
            catch (e_7_1) { e_7 = { error: e_7_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_7) throw e_7.error; }
            }
            // make inputs and requires a top thing
            var newObj = {};
            newObj['__inputs'] = inputs;
            newObj['__requires'] = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(requires, ['id']);
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(newObj, saveModel);
            return newObj;
        })
            .catch(function (err) {
            console.log('Export failed:', err);
            return {
                error: err,
            };
        });
    };
    return DashboardExporter;
}());



/***/ }),

/***/ "./public/app/features/dashboard/components/DashExportModal/index.ts":
/*!***************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashExportModal/index.ts ***!
  \***************************************************************************/
/*! exports provided: DashboardExporter, DashExportCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _DashboardExporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DashboardExporter */ "./public/app/features/dashboard/components/DashExportModal/DashboardExporter.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashboardExporter", function() { return _DashboardExporter__WEBPACK_IMPORTED_MODULE_0__["DashboardExporter"]; });

/* harmony import */ var _DashExportCtrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DashExportCtrl */ "./public/app/features/dashboard/components/DashExportModal/DashExportCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashExportCtrl", function() { return _DashExportCtrl__WEBPACK_IMPORTED_MODULE_1__["DashExportCtrl"]; });





/***/ }),

/***/ "./public/app/features/dashboard/components/DashLinks/DashLinksContainerCtrl.ts":
/*!**************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashLinks/DashLinksContainerCtrl.ts ***!
  \**************************************************************************************/
/*! exports provided: DashLinksContainerCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashLinksContainerCtrl", function() { return DashLinksContainerCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _DashLinksEditorCtrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./DashLinksEditorCtrl */ "./public/app/features/dashboard/components/DashLinks/DashLinksEditorCtrl.ts");



function dashLinksContainer() {
    return {
        scope: {
            links: '=',
            dashboard: '=',
        },
        restrict: 'E',
        controller: 'DashLinksContainerCtrl',
        template: '<dash-link ng-repeat="link in generatedLinks" link="link"></dash-link>',
        link: function () { },
    };
}
/** @ngInject */
function dashLink($compile, $sanitize, linkSrv) {
    return {
        restrict: 'E',
        link: function (scope, elem) {
            var link = scope.link;
            var dashboard = scope.dashboard;
            var template = '<div class="gf-form">' +
                '<a class="pointer gf-form-label" data-placement="bottom"' +
                (link.asDropdown ? ' ng-click="fillDropdown(link)" data-toggle="dropdown"' : '') +
                '>' +
                '<i></i> <span></span></a>';
            if (link.asDropdown) {
                template +=
                    '<ul class="dropdown-menu" role="menu">' +
                        '<li ng-repeat="dash in link.searchHits">' +
                        '<a href="{{dash.url}}" target="{{dash.target}}">{{dash.title}}</a>' +
                        '</li>' +
                        '</ul>';
            }
            template += '</div>';
            elem.html(template);
            $compile(elem.contents())(scope);
            function update() {
                var linkInfo = linkSrv.getAnchorInfo(link);
                var anchor = elem.find('a');
                var span = elem.find('span');
                span.text(linkInfo.title);
                if (!link.asDropdown) {
                    anchor.attr('href', linkInfo.href);
                    sanitizeAnchor();
                }
                anchor.attr('data-placement', 'bottom');
                // tooltip
                anchor.tooltip({
                    title: $sanitize(scope.link.tooltip),
                    html: true,
                    container: 'body',
                });
            }
            function sanitizeAnchor() {
                var anchor = elem.find('a');
                var anchorSanitized = $sanitize(anchor.parent().html());
                anchor.parent().html(anchorSanitized);
            }
            elem.find('i').attr('class', 'fa fa-fw ' + scope.link.icon);
            elem.find('a').attr('target', scope.link.target);
            // fix for menus on the far right
            if (link.asDropdown && scope.$last) {
                elem.find('.dropdown-menu').addClass('pull-right');
            }
            update();
            dashboard.events.on('refresh', update, scope);
        },
    };
}
var DashLinksContainerCtrl = /** @class */ (function () {
    /** @ngInject */
    function DashLinksContainerCtrl($scope, $rootScope, $q, backendSrv, dashboardSrv, linkSrv) {
        var currentDashId = dashboardSrv.getCurrent().id;
        function buildLinks(linkDef) {
            if (linkDef.type === 'dashboards') {
                if (!linkDef.tags) {
                    console.log('Dashboard link missing tag');
                    return $q.when([]);
                }
                if (linkDef.asDropdown) {
                    return $q.when([
                        {
                            title: linkDef.title,
                            tags: linkDef.tags,
                            keepTime: linkDef.keepTime,
                            includeVars: linkDef.includeVars,
                            target: linkDef.targetBlank ? '_blank' : '_self',
                            icon: 'fa fa-bars',
                            asDropdown: true,
                        },
                    ]);
                }
                return $scope.searchDashboards(linkDef, 7);
            }
            if (linkDef.type === 'link') {
                return $q.when([
                    {
                        url: linkDef.url,
                        title: linkDef.title,
                        // @ts-ignore
                        icon: _DashLinksEditorCtrl__WEBPACK_IMPORTED_MODULE_2__["iconMap"][linkDef.icon],
                        tooltip: linkDef.tooltip,
                        target: linkDef.targetBlank ? '_blank' : '_self',
                        keepTime: linkDef.keepTime,
                        includeVars: linkDef.includeVars,
                    },
                ]);
            }
            return $q.when([]);
        }
        function updateDashLinks() {
            var promises = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map($scope.links, buildLinks);
            $q.all(promises).then(function (results) {
                $scope.generatedLinks = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.flatten(results);
            });
        }
        $scope.searchDashboards = function (link, limit) {
            return backendSrv.search({ tag: link.tags, limit: limit }).then(function (results) {
                return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.reduce(results, function (memo, dash) {
                    // do not add current dashboard
                    if (dash.id !== currentDashId) {
                        memo.push({
                            title: dash.title,
                            url: dash.url,
                            target: link.target === '_self' ? '' : link.target,
                            icon: 'fa fa-th-large',
                            keepTime: link.keepTime,
                            includeVars: link.includeVars,
                        });
                    }
                    return memo;
                }, []);
            });
        };
        $scope.fillDropdown = function (link) {
            $scope.searchDashboards(link, 100).then(function (results) {
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(results, function (hit) {
                    hit.url = linkSrv.getLinkUrl(hit);
                });
                link.searchHits = results;
            });
        };
        updateDashLinks();
        $rootScope.onAppEvent('dash-links-updated', updateDashLinks, $scope);
    }
    return DashLinksContainerCtrl;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives').directive('dashLinksContainer', dashLinksContainer);
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives').directive('dashLink', dashLink);
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives').controller('DashLinksContainerCtrl', DashLinksContainerCtrl);


/***/ }),

/***/ "./public/app/features/dashboard/components/DashLinks/DashLinksEditorCtrl.ts":
/*!***********************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashLinks/DashLinksEditorCtrl.ts ***!
  \***********************************************************************************/
/*! exports provided: iconMap, DashLinksEditorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iconMap", function() { return iconMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashLinksEditorCtrl", function() { return DashLinksEditorCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


var iconMap = {
    'external link': 'fa-external-link',
    dashboard: 'fa-th-large',
    question: 'fa-question',
    info: 'fa-info',
    bolt: 'fa-bolt',
    doc: 'fa-file-text-o',
    cloud: 'fa-cloud',
};
var DashLinksEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function DashLinksEditorCtrl($scope, $rootScope) {
        var _this = this;
        this.emptyListCta = {
            title: 'There are no dashboard links added yet',
            buttonIcon: 'gicon gicon-link',
            buttonTitle: 'Add Dashboard Link',
            infoBox: {
                __html: "<p>\n      Dashboard Links allow you to place links to other dashboards and web sites directly in below the dashboard\n      header.\n    </p>",
            },
            infoBoxTitle: 'What are Dashboard Links?',
        };
        this.setupNew = function () {
            _this.mode = 'new';
            _this.link = { type: 'dashboards', icon: 'external link' };
        };
        this.iconMap = iconMap;
        this.dashboard.links = this.dashboard.links || [];
        this.mode = 'list';
        $scope.$on('$destroy', function () {
            $rootScope.appEvent('dash-links-updated');
        });
    }
    DashLinksEditorCtrl.prototype.backToList = function () {
        this.mode = 'list';
    };
    DashLinksEditorCtrl.prototype.addLink = function () {
        this.dashboard.links.push(this.link);
        this.mode = 'list';
        this.dashboard.updateSubmenuVisibility();
    };
    DashLinksEditorCtrl.prototype.editLink = function (link) {
        this.link = link;
        this.mode = 'edit';
        console.log(this.link);
    };
    DashLinksEditorCtrl.prototype.saveLink = function () {
        this.backToList();
    };
    DashLinksEditorCtrl.prototype.moveLink = function (index, dir) {
        // @ts-ignore
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.move(this.dashboard.links, index, index + dir);
    };
    DashLinksEditorCtrl.prototype.deleteLink = function (index) {
        this.dashboard.links.splice(index, 1);
        this.dashboard.updateSubmenuVisibility();
    };
    return DashLinksEditorCtrl;
}());

function dashLinksEditor() {
    return {
        restrict: 'E',
        controller: DashLinksEditorCtrl,
        templateUrl: 'public/app/features/dashboard/components/DashLinks/editor.html',
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            dashboard: '=',
        },
    };
}
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives').directive('dashLinksEditor', dashLinksEditor);


/***/ }),

/***/ "./public/app/features/dashboard/components/DashLinks/index.ts":
/*!*********************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashLinks/index.ts ***!
  \*********************************************************************/
/*! exports provided: DashLinksContainerCtrl, DashLinksEditorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _DashLinksContainerCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DashLinksContainerCtrl */ "./public/app/features/dashboard/components/DashLinks/DashLinksContainerCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashLinksContainerCtrl", function() { return _DashLinksContainerCtrl__WEBPACK_IMPORTED_MODULE_0__["DashLinksContainerCtrl"]; });

/* harmony import */ var _DashLinksEditorCtrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DashLinksEditorCtrl */ "./public/app/features/dashboard/components/DashLinks/DashLinksEditorCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashLinksEditorCtrl", function() { return _DashLinksEditorCtrl__WEBPACK_IMPORTED_MODULE_1__["DashLinksEditorCtrl"]; });





/***/ }),

/***/ "./public/app/features/dashboard/components/DashNav/DashNav.tsx":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashNav/DashNav.tsx ***!
  \**********************************************************************/
/*! exports provided: DashNav, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashNav", function() { return DashNav; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var _DashNavButton__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./DashNavButton */ "./public/app/features/dashboard/components/DashNav/DashNavButton.tsx");
/* harmony import */ var _DashNavTimeControls__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DashNavTimeControls */ "./public/app/features/dashboard/components/DashNav/DashNavTimeControls.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");

// Libaries


// Utils & Services

// Components



// State

var DashNav = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DashNav, _super);
    function DashNav(props) {
        var _this = _super.call(this, props) || this;
        _this.onDahboardNameClick = function () {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["appEvents"].emit('show-dash-search');
        };
        _this.onFolderNameClick = function () {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["appEvents"].emit('show-dash-search', {
                query: 'folder:current',
            });
        };
        _this.onClose = function () {
            if (_this.props.editview) {
                _this.props.updateLocation({
                    query: { editview: null },
                    partial: true,
                });
            }
            else {
                _this.props.updateLocation({
                    query: { panelId: null, edit: null, fullscreen: null, tab: null },
                    partial: true,
                });
            }
        };
        _this.onToggleTVMode = function () {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["appEvents"].emit('toggle-kiosk-mode');
        };
        _this.onSave = function () {
            var $injector = _this.props.$injector;
            var dashboardSrv = $injector.get('dashboardSrv');
            dashboardSrv.saveDashboard();
        };
        _this.onOpenSettings = function () {
            _this.props.updateLocation({
                query: { editview: 'settings' },
                partial: true,
            });
        };
        _this.onStarDashboard = function () {
            var _a = _this.props, dashboard = _a.dashboard, $injector = _a.$injector;
            var dashboardSrv = $injector.get('dashboardSrv');
            dashboardSrv.starDashboard(dashboard.id, dashboard.meta.isStarred).then(function (newState) {
                dashboard.meta.isStarred = newState;
                _this.forceUpdate();
            });
        };
        _this.onPlaylistPrev = function () {
            _this.playlistSrv.prev();
        };
        _this.onPlaylistNext = function () {
            _this.playlistSrv.next();
        };
        _this.onPlaylistStop = function () {
            _this.playlistSrv.stop();
            _this.forceUpdate();
        };
        _this.onOpenShare = function () {
            var $rootScope = _this.props.$injector.get('$rootScope');
            var modalScope = $rootScope.$new();
            modalScope.tabIndex = 0;
            modalScope.dashboard = _this.props.dashboard;
            app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["appEvents"].emit('show-modal', {
                src: 'public/app/features/dashboard/components/ShareModal/template.html',
                scope: modalScope,
            });
        };
        _this.playlistSrv = _this.props.$injector.get('playlistSrv');
        return _this;
    }
    DashNav.prototype.renderDashboardTitleSearchButton = function () {
        var dashboard = this.props.dashboard;
        var folderTitle = dashboard.meta.folderTitle;
        var haveFolder = dashboard.meta.folderId > 0;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar-page-btn" },
                    !this.isInFullscreenOrSettings && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "gicon gicon-dashboard" }),
                    haveFolder && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "navbar-page-btn__folder", onClick: this.onFolderNameClick }, folderTitle),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-chevron-right navbar-page-btn__folder-icon" }))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { onClick: this.onDahboardNameClick },
                        dashboard.title,
                        " ",
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-down navbar-page-btn__search" })))),
            this.isSettings && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "navbar-settings-title" }, "\u00A0/ Settings"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar__spacer" })));
    };
    Object.defineProperty(DashNav.prototype, "isInFullscreenOrSettings", {
        get: function () {
            return this.props.editview || this.props.isFullscreen;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(DashNav.prototype, "isSettings", {
        get: function () {
            return this.props.editview;
        },
        enumerable: true,
        configurable: true
    });
    DashNav.prototype.renderBackButton = function () {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar-edit" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["Tooltip"], { content: "Go back (Esc)" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "navbar-edit__back-btn", onClick: this.onClose },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-arrow-left" })))));
    };
    DashNav.prototype.render = function () {
        var _a = this.props, dashboard = _a.dashboard, onAddPanel = _a.onAddPanel, location = _a.location, $injector = _a.$injector;
        var _b = dashboard.meta, canStar = _b.canStar, canSave = _b.canSave, canShare = _b.canShare, showSettings = _b.showSettings, isStarred = _b.isStarred;
        var snapshot = dashboard.snapshot;
        var snapshotUrl = snapshot && snapshot.originalUrl;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar" },
            this.isInFullscreenOrSettings && this.renderBackButton(),
            this.renderDashboardTitleSearchButton(),
            this.playlistSrv.isPlaying && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar-buttons navbar-buttons--playlist" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Go to previous dashboard", classSuffix: "tight", icon: "fa fa-step-backward", onClick: this.onPlaylistPrev }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Stop playlist", classSuffix: "tight", icon: "fa fa-stop", onClick: this.onPlaylistStop }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Go to next dashboard", classSuffix: "tight", icon: "fa fa-forward", onClick: this.onPlaylistNext }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar-buttons navbar-buttons--actions" },
                canSave && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Add panel", classSuffix: "add-panel", icon: "gicon gicon-add-panel", onClick: onAddPanel })),
                canStar && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Mark as favorite", classSuffix: "star", icon: "" + (isStarred ? 'fa fa-star' : 'fa fa-star-o'), onClick: this.onStarDashboard })),
                canShare && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Share dashboard", classSuffix: "share", icon: "fa fa-share-square-o", onClick: this.onOpenShare })),
                canSave && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Save dashboard", classSuffix: "save", icon: "fa fa-save", onClick: this.onSave })),
                snapshotUrl && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Open original dashboard", classSuffix: "snapshot-origin", icon: "gicon gicon-link", href: snapshotUrl })),
                showSettings && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Dashboard settings", classSuffix: "settings", icon: "gicon gicon-cog", onClick: this.onOpenSettings }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar-buttons navbar-buttons--tv" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavButton__WEBPACK_IMPORTED_MODULE_4__["DashNavButton"], { tooltip: "Cycle view mode", classSuffix: "tv", icon: "fa fa-desktop", onClick: this.onToggleTVMode })),
            !dashboard.timepicker.hidden && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "navbar-buttons" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_DashNavTimeControls__WEBPACK_IMPORTED_MODULE_5__["DashNavTimeControls"], { "$injector": $injector, dashboard: dashboard, location: location, updateLocation: app_core_actions__WEBPACK_IMPORTED_MODULE_7__["updateLocation"] })))));
    };
    return DashNav;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var mapStateToProps = function (state) { return ({
    location: state.location,
}); };
var mapDispatchToProps = {
    updateLocation: app_core_actions__WEBPACK_IMPORTED_MODULE_7__["updateLocation"],
};
/* harmony default export */ __webpack_exports__["default"] = (Object(react_redux__WEBPACK_IMPORTED_MODULE_2__["connect"])(mapStateToProps, mapDispatchToProps)(DashNav));


/***/ }),

/***/ "./public/app/features/dashboard/components/DashNav/DashNavButton.tsx":
/*!****************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashNav/DashNavButton.tsx ***!
  \****************************************************************************/
/*! exports provided: DashNavButton */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashNavButton", function() { return DashNavButton; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
// Libraries

// Components

var DashNavButton = function (_a) {
    var icon = _a.icon, tooltip = _a.tooltip, classSuffix = _a.classSuffix, onClick = _a.onClick, href = _a.href;
    if (onClick) {
        return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["Tooltip"], { content: tooltip },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { className: "btn navbar-button navbar-button--" + classSuffix, onClick: onClick, "aria-label": tooltip + " navbar button" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: icon }))));
    }
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["Tooltip"], { content: tooltip },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", { className: "btn navbar-button navbar-button--" + classSuffix, href: href },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: icon }))));
};


/***/ }),

/***/ "./public/app/features/dashboard/components/DashNav/DashNavTimeControls.tsx":
/*!**********************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashNav/DashNavTimeControls.tsx ***!
  \**********************************************************************************/
/*! exports provided: DashNavTimeControls */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashNavTimeControls", function() { return DashNavTimeControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/dashboard/services/TimeSrv */ "./public/app/features/dashboard/services/TimeSrv.ts");
/* harmony import */ var _grafana_ui_src_components_TimePicker_TimePicker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/ui/src/components/TimePicker/TimePicker */ "./packages/grafana-ui/src/components/TimePicker/TimePicker.tsx");

// Libaries


// Components

// Utils & Services


var DashNavTimeControls = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DashNavTimeControls, _super);
    function DashNavTimeControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.timeSrv = Object(app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_4__["getTimeSrv"])();
        _this.$rootScope = _this.props.$injector.get('$rootScope');
        _this.onChangeRefreshInterval = function (interval) {
            _this.timeSrv.setAutoRefresh(interval);
            _this.forceUpdate();
        };
        _this.onRefresh = function () {
            _this.timeSrv.refreshDashboard();
            return Promise.resolve();
        };
        _this.onMoveBack = function () {
            _this.$rootScope.appEvent('shift-time', -1);
        };
        _this.onMoveForward = function () {
            _this.$rootScope.appEvent('shift-time', 1);
        };
        _this.onChangeTimePicker = function (timeRange) {
            var dashboard = _this.props.dashboard;
            var panel = dashboard.timepicker;
            var hasDelay = panel.nowDelay && timeRange.raw.to === 'now';
            var adjustedFrom = _grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateMath"].isMathString(timeRange.raw.from) ? timeRange.raw.from : timeRange.from;
            var adjustedTo = _grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateMath"].isMathString(timeRange.raw.to) ? timeRange.raw.to : timeRange.to;
            var nextRange = {
                from: adjustedFrom,
                to: hasDelay ? 'now-' + panel.nowDelay : adjustedTo,
            };
            _this.timeSrv.setTime(nextRange);
        };
        _this.onZoom = function () {
            _this.$rootScope.appEvent('zoom-out', 2);
        };
        _this.setActiveTimeOption = function (timeOptions, rawTimeRange) {
            return timeOptions.map(function (option) {
                if (option.to === rawTimeRange.to && option.from === rawTimeRange.from) {
                    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, option, { active: true });
                }
                return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, option, { active: false });
            });
        };
        return _this;
    }
    Object.defineProperty(DashNavTimeControls.prototype, "refreshParamInUrl", {
        get: function () {
            return this.props.location.query.refresh;
        },
        enumerable: true,
        configurable: true
    });
    DashNavTimeControls.prototype.render = function () {
        var dashboard = this.props.dashboard;
        var intervals = dashboard.timepicker.refresh_intervals;
        var timePickerValue = this.timeSrv.timeRange();
        var timeZone = dashboard.getTimezone();
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "dashboard-timepicker-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["TimePicker"], { value: timePickerValue, onChange: this.onChangeTimePicker, timeZone: timeZone, onMoveBackward: this.onMoveBack, onMoveForward: this.onMoveForward, onZoom: this.onZoom, selectOptions: this.setActiveTimeOption(_grafana_ui_src_components_TimePicker_TimePicker__WEBPACK_IMPORTED_MODULE_5__["defaultSelectOptions"], timePickerValue.raw) }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["RefreshPicker"], { onIntervalChanged: this.onChangeRefreshInterval, onRefresh: this.onRefresh, value: dashboard.refresh, intervals: intervals, tooltip: "Refresh dashboard" })));
    };
    return DashNavTimeControls;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));



/***/ }),

/***/ "./public/app/features/dashboard/components/DashNav/index.ts":
/*!*******************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashNav/index.ts ***!
  \*******************************************************************/
/*! exports provided: DashNav */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _DashNav__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DashNav */ "./public/app/features/dashboard/components/DashNav/DashNav.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashNav", function() { return _DashNav__WEBPACK_IMPORTED_MODULE_0__["default"]; });





/***/ }),

/***/ "./public/app/features/dashboard/components/DashboardPermissions/DashboardPermissions.tsx":
/*!************************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashboardPermissions/DashboardPermissions.tsx ***!
  \************************************************************************************************/
/*! exports provided: DashboardPermissions, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardPermissions", function() { return DashboardPermissions; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_components_Animations_SlideDown__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/components/Animations/SlideDown */ "./public/app/core/components/Animations/SlideDown.tsx");
/* harmony import */ var _state_actions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../state/actions */ "./public/app/features/dashboard/state/actions.ts");
/* harmony import */ var app_core_components_PermissionList_PermissionList__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/components/PermissionList/PermissionList */ "./public/app/core/components/PermissionList/PermissionList.tsx");
/* harmony import */ var app_core_components_PermissionList_AddPermission__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/components/PermissionList/AddPermission */ "./public/app/core/components/PermissionList/AddPermission.tsx");
/* harmony import */ var app_core_components_PermissionList_PermissionsInfo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/components/PermissionList/PermissionsInfo */ "./public/app/core/components/PermissionList/PermissionsInfo.tsx");
/* harmony import */ var app_core_utils_connectWithReduxStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/utils/connectWithReduxStore */ "./public/app/core/utils/connectWithReduxStore.tsx");









var DashboardPermissions = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DashboardPermissions, _super);
    function DashboardPermissions(props) {
        var _this = _super.call(this, props) || this;
        _this.onOpenAddPermissions = function () {
            _this.setState({ isAdding: true });
        };
        _this.onRemoveItem = function (item) {
            _this.props.removeDashboardPermission(_this.props.dashboardId, item);
        };
        _this.onPermissionChanged = function (item, level) {
            _this.props.updateDashboardPermission(_this.props.dashboardId, item, level);
        };
        _this.onAddPermission = function (newItem) {
            return _this.props.addDashboardPermission(_this.props.dashboardId, newItem);
        };
        _this.onCancelAddPermission = function () {
            _this.setState({ isAdding: false });
        };
        _this.state = {
            isAdding: false,
        };
        return _this;
    }
    DashboardPermissions.prototype.componentDidMount = function () {
        this.props.getDashboardPermissions(this.props.dashboardId);
    };
    DashboardPermissions.prototype.render = function () {
        var _a = this.props, permissions = _a.permissions, folder = _a.folder;
        var isAdding = this.state.isAdding;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "dashboard-settings__header" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-action-bar" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "d-inline-block" }, "Permissions"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Tooltip"], { placement: "auto", content: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_PermissionList_PermissionsInfo__WEBPACK_IMPORTED_MODULE_7__["default"], null) },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-sub-heading-icon" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "gicon gicon-question gicon--has-hover" }))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "page-action-bar__spacer" }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "btn btn-primary pull-right", onClick: this.onOpenAddPermissions, disabled: isAdding }, "Add Permission"))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Animations_SlideDown__WEBPACK_IMPORTED_MODULE_3__["SlideDown"], { in: isAdding },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_PermissionList_AddPermission__WEBPACK_IMPORTED_MODULE_6__["default"], { onAddPermission: this.onAddPermission, onCancel: this.onCancelAddPermission })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_PermissionList_PermissionList__WEBPACK_IMPORTED_MODULE_5__["default"], { items: permissions, onRemoveItem: this.onRemoveItem, onPermissionChanged: this.onPermissionChanged, isFetching: false, folderInfo: folder })));
    };
    return DashboardPermissions;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var mapStateToProps = function (state) { return ({
    permissions: state.dashboard.permissions,
}); };
var mapDispatchToProps = {
    getDashboardPermissions: _state_actions__WEBPACK_IMPORTED_MODULE_4__["getDashboardPermissions"],
    addDashboardPermission: _state_actions__WEBPACK_IMPORTED_MODULE_4__["addDashboardPermission"],
    removeDashboardPermission: _state_actions__WEBPACK_IMPORTED_MODULE_4__["removeDashboardPermission"],
    updateDashboardPermission: _state_actions__WEBPACK_IMPORTED_MODULE_4__["updateDashboardPermission"],
};
/* harmony default export */ __webpack_exports__["default"] = (Object(app_core_utils_connectWithReduxStore__WEBPACK_IMPORTED_MODULE_8__["connectWithStore"])(DashboardPermissions, mapStateToProps, mapDispatchToProps));


/***/ }),

/***/ "./public/app/features/dashboard/components/DashboardSettings/DashboardSettings.tsx":
/*!******************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashboardSettings/DashboardSettings.tsx ***!
  \******************************************************************************************/
/*! exports provided: DashboardSettings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardSettings", function() { return DashboardSettings; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");

// Libaries

// Utils & Services

var DashboardSettings = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DashboardSettings, _super);
    function DashboardSettings() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DashboardSettings.prototype.componentDidMount = function () {
        var loader = Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getAngularLoader"])();
        var template = '<dashboard-settings dashboard="dashboard" class="dashboard-settings" />';
        var scopeProps = { dashboard: this.props.dashboard };
        this.angularCmp = loader.load(this.element, scopeProps, template);
    };
    DashboardSettings.prototype.componentWillUnmount = function () {
        if (this.angularCmp) {
            this.angularCmp.destroy();
        }
    };
    DashboardSettings.prototype.render = function () {
        var _this = this;
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "panel-height-helper", ref: function (element) { return (_this.element = element); } });
    };
    return DashboardSettings;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/features/dashboard/components/DashboardSettings/SettingsCtrl.ts":
/*!************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashboardSettings/SettingsCtrl.ts ***!
  \************************************************************************************/
/*! exports provided: SettingsCtrl, dashboardSettings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SettingsCtrl", function() { return SettingsCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardSettings", function() { return dashboardSettings; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");






var SettingsCtrl = /** @class */ (function () {
    /** @ngInject */
    function SettingsCtrl($scope, $route, $location, $rootScope, backendSrv, dashboardSrv) {
        var _this = this;
        this.$scope = $scope;
        this.$route = $route;
        this.$location = $location;
        this.$rootScope = $rootScope;
        this.backendSrv = backendSrv;
        this.dashboardSrv = dashboardSrv;
        // temp hack for annotations and variables editors
        // that rely on inherited scope
        $scope.dashboard = this.dashboard;
        this.$scope.$on('$destroy', function () {
            _this.dashboard.updateSubmenuVisibility();
            setTimeout(function () {
                _this.$rootScope.appEvent('dash-scroll', { restore: true });
                _this.dashboard.startRefresh();
            });
        });
        this.canSaveAs = app_core_core__WEBPACK_IMPORTED_MODULE_1__["contextSrv"].hasEditPermissionInFolders;
        this.canSave = this.dashboard.meta.canSave;
        this.canDelete = this.dashboard.meta.canSave;
        this.buildSectionList();
        this.onRouteUpdated();
        this.$rootScope.onAppEvent('$routeUpdate', this.onRouteUpdated.bind(this), $scope);
        this.$rootScope.appEvent('dash-scroll', { animate: false, pos: 0 });
        this.$rootScope.onAppEvent('dashboard-saved', this.onPostSave.bind(this), $scope);
    }
    SettingsCtrl.prototype.buildSectionList = function () {
        var e_1, _a;
        this.sections = [];
        if (this.dashboard.meta.canEdit) {
            this.sections.push({
                title: 'General',
                id: 'settings',
                icon: 'gicon gicon-preferences',
            });
            this.sections.push({
                title: 'Annotations',
                id: 'annotations',
                icon: 'gicon gicon-annotation',
            });
            this.sections.push({
                title: 'Variables',
                id: 'templating',
                icon: 'gicon gicon-variable',
            });
            this.sections.push({
                title: 'Links',
                id: 'links',
                icon: 'gicon gicon-link',
            });
        }
        if (this.dashboard.id && this.dashboard.meta.canSave) {
            this.sections.push({
                title: 'Versions',
                id: 'versions',
                icon: 'fa fa-fw fa-history',
            });
        }
        if (this.dashboard.id && this.dashboard.meta.canAdmin) {
            this.sections.push({
                title: 'Permissions',
                id: 'permissions',
                icon: 'fa fa-fw fa-lock',
            });
        }
        if (this.dashboard.meta.canMakeEditable) {
            this.sections.push({
                title: 'General',
                icon: 'gicon gicon-preferences',
                id: 'make_editable',
            });
        }
        this.sections.push({
            title: 'JSON Model',
            id: 'dashboard_json',
            icon: 'gicon gicon-json',
        });
        var params = this.$location.search();
        var url = this.$location.path();
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
                var section = _c.value;
                var sectionParams = lodash__WEBPACK_IMPORTED_MODULE_3___default.a.defaults({ editview: section.id }, params);
                section.url = app_core_config__WEBPACK_IMPORTED_MODULE_5__["default"].appSubUrl + url + '?' + jquery__WEBPACK_IMPORTED_MODULE_2___default.a.param(sectionParams);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    SettingsCtrl.prototype.onRouteUpdated = function () {
        this.viewId = this.$location.search().editview;
        if (this.viewId) {
            this.json = angular__WEBPACK_IMPORTED_MODULE_4___default.a.toJson(this.dashboard.getSaveModelClone(), true);
        }
        if (this.viewId === 'settings' && this.dashboard.meta.canMakeEditable) {
            this.viewId = 'make_editable';
        }
        var currentSection = lodash__WEBPACK_IMPORTED_MODULE_3___default.a.find(this.sections, { id: this.viewId });
        if (!currentSection) {
            this.sections.unshift({
                title: 'Not found',
                id: '404',
                icon: 'fa fa-fw fa-warning',
            });
            this.viewId = '404';
        }
    };
    SettingsCtrl.prototype.openSaveAsModal = function () {
        this.dashboardSrv.showSaveAsModal();
    };
    SettingsCtrl.prototype.saveDashboard = function () {
        this.dashboardSrv.saveDashboard();
    };
    SettingsCtrl.prototype.saveDashboardJson = function () {
        var _this = this;
        this.dashboardSrv.saveJSONDashboard(this.json).then(function () {
            _this.$route.reload();
        });
    };
    SettingsCtrl.prototype.onPostSave = function () {
        this.hasUnsavedFolderChange = false;
    };
    SettingsCtrl.prototype.hideSettings = function () {
        var _this = this;
        var urlParams = this.$location.search();
        delete urlParams.editview;
        setTimeout(function () {
            _this.$rootScope.$apply(function () {
                _this.$location.search(urlParams);
            });
        });
    };
    SettingsCtrl.prototype.makeEditable = function () {
        this.dashboard.editable = true;
        this.dashboard.meta.canMakeEditable = false;
        this.dashboard.meta.canEdit = true;
        this.dashboard.meta.canSave = true;
        this.canDelete = true;
        this.viewId = 'settings';
        this.buildSectionList();
        var currentSection = lodash__WEBPACK_IMPORTED_MODULE_3___default.a.find(this.sections, { id: this.viewId });
        this.$location.url(currentSection.url);
    };
    SettingsCtrl.prototype.deleteDashboard = function () {
        var _this = this;
        var confirmText = '';
        var text2 = this.dashboard.title;
        if (this.dashboard.meta.provisioned) {
            app_core_core__WEBPACK_IMPORTED_MODULE_1__["appEvents"].emit('confirm-modal', {
                title: 'Cannot delete provisioned dashboard',
                text: "\n          This dashboard is managed by Grafanas provisioning and cannot be deleted. Remove the dashboard from the\n          config file to delete it.\n        ",
                text2: "\n          <i>See <a class=\"external-link\" href=\"http://docs.grafana.org/administration/provisioning/#dashboards\" target=\"_blank\">\n          documentation</a> for more information about provisioning.</i>\n          </br>\n          File path: " + this.dashboard.meta.provisionedExternalId + "\n        ",
                text2htmlBind: true,
                icon: 'fa-trash',
                noText: 'OK',
            });
            return;
        }
        var alerts = lodash__WEBPACK_IMPORTED_MODULE_3___default.a.sumBy(this.dashboard.panels, function (panel) {
            return panel.alert ? 1 : 0;
        });
        if (alerts > 0) {
            confirmText = 'DELETE';
            text2 = "This dashboard contains " + alerts + " alerts. Deleting this dashboard will also delete those alerts";
        }
        app_core_core__WEBPACK_IMPORTED_MODULE_1__["appEvents"].emit('confirm-modal', {
            title: 'Delete',
            text: 'Do you want to delete this dashboard?',
            text2: text2,
            icon: 'fa-trash',
            confirmText: confirmText,
            yesText: 'Delete',
            onConfirm: function () {
                _this.dashboard.meta.canSave = false;
                _this.deleteDashboardConfirmed();
            },
        });
    };
    SettingsCtrl.prototype.deleteDashboardConfirmed = function () {
        var _this = this;
        this.backendSrv.deleteDashboard(this.dashboard.uid, false).then(function () {
            app_core_core__WEBPACK_IMPORTED_MODULE_1__["appEvents"].emit('alert-success', ['Dashboard Deleted', _this.dashboard.title + ' has been deleted']);
            _this.$location.url('/');
        });
    };
    SettingsCtrl.prototype.onFolderChange = function (folder) {
        this.dashboard.meta.folderId = folder.id;
        this.dashboard.meta.folderTitle = folder.title;
        this.hasUnsavedFolderChange = true;
    };
    SettingsCtrl.prototype.getFolder = function () {
        return {
            id: this.dashboard.meta.folderId,
            title: this.dashboard.meta.folderTitle,
            url: this.dashboard.meta.folderUrl,
        };
    };
    return SettingsCtrl;
}());

function dashboardSettings() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/DashboardSettings/template.html',
        controller: SettingsCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        transclude: true,
        scope: { dashboard: '=' },
    };
}
app_core_core__WEBPACK_IMPORTED_MODULE_1__["coreModule"].directive('dashboardSettings', dashboardSettings);


/***/ }),

/***/ "./public/app/features/dashboard/components/DashboardSettings/TimePickerSettings.ts":
/*!******************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashboardSettings/TimePickerSettings.ts ***!
  \******************************************************************************************/
/*! exports provided: TimePickerCtrl, TimePickerSettings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimePickerCtrl", function() { return TimePickerCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimePickerSettings", function() { return TimePickerSettings; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var TimePickerCtrl = /** @class */ (function () {
    function TimePickerCtrl() {
        this.panel = this.dashboard.timepicker;
        this.panel.refresh_intervals = this.panel.refresh_intervals || [
            '5s',
            '10s',
            '30s',
            '1m',
            '5m',
            '15m',
            '30m',
            '1h',
            '2h',
            '1d',
        ];
    }
    return TimePickerCtrl;
}());

var template = "\n<div class=\"editor-row\">\n\t<h5 class=\"section-heading\">Time Options</h5>\n\n  <div class=\"gf-form-group\">\n\t\t<div class=\"gf-form\">\n\t\t\t<label class=\"gf-form-label width-10\">Timezone</label>\n\t\t\t<div class=\"gf-form-select-wrapper\">\n\t\t\t\t<select ng-model=\"ctrl.dashboard.timezone\" class='gf-form-input' ng-options=\"f.value as f.text for f in\n\t\t\t\t  [{value: '', text: 'Default'}, {value: 'browser', text: 'Local browser time'},{value: 'utc', text: 'UTC'}]\">\n\t\t\t\t</select>\n\t\t\t</div>\n\t\t</div>\n\n\t\t<div class=\"gf-form\">\n\t\t\t<span class=\"gf-form-label width-10\">Auto-refresh</span>\n\t\t\t<input type=\"text\" class=\"gf-form-input max-width-25\" ng-model=\"ctrl.panel.refresh_intervals\" array-join>\n\t\t</div>\n\t\t<div class=\"gf-form\">\n\t\t\t<span class=\"gf-form-label width-10\">Now delay now-</span>\n\t\t\t<input type=\"text\" class=\"gf-form-input max-width-25\" ng-model=\"ctrl.panel.nowDelay\"\n\t\t\t    placeholder=\"0m\"\n\t\t\t    valid-time-span\n\t\t\t    bs-tooltip=\"'Enter 1m to ignore the last minute (because it can contain incomplete metrics)'\"\n \t\t\t\t  data-placement=\"right\">\n\t\t</div>\n\n\t\t<gf-form-switch class=\"gf-form\" label=\"Hide time picker\" checked=\"ctrl.panel.hidden\" label-class=\"width-10\">\n\t\t</gf-form-switch>\n\t</div>\n</div>\n";
function TimePickerSettings() {
    return {
        restrict: 'E',
        template: template,
        controller: TimePickerCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            dashboard: '=',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('gfTimePickerSettings', TimePickerSettings);


/***/ }),

/***/ "./public/app/features/dashboard/components/DashboardSettings/index.ts":
/*!*****************************************************************************!*\
  !*** ./public/app/features/dashboard/components/DashboardSettings/index.ts ***!
  \*****************************************************************************/
/*! exports provided: SettingsCtrl, DashboardSettings, TimePickerSettings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _SettingsCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SettingsCtrl */ "./public/app/features/dashboard/components/DashboardSettings/SettingsCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SettingsCtrl", function() { return _SettingsCtrl__WEBPACK_IMPORTED_MODULE_0__["SettingsCtrl"]; });

/* harmony import */ var _DashboardSettings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DashboardSettings */ "./public/app/features/dashboard/components/DashboardSettings/DashboardSettings.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashboardSettings", function() { return _DashboardSettings__WEBPACK_IMPORTED_MODULE_1__["DashboardSettings"]; });

/* harmony import */ var _TimePickerSettings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TimePickerSettings */ "./public/app/features/dashboard/components/DashboardSettings/TimePickerSettings.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TimePickerSettings", function() { return _TimePickerSettings__WEBPACK_IMPORTED_MODULE_2__["TimePickerSettings"]; });






/***/ }),

/***/ "./public/app/features/dashboard/components/ExportDataModal/ExportDataModalCtrl.ts":
/*!*****************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/ExportDataModal/ExportDataModalCtrl.ts ***!
  \*****************************************************************************************/
/*! exports provided: ExportDataModalCtrl, exportDataModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExportDataModalCtrl", function() { return ExportDataModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exportDataModal", function() { return exportDataModal; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_file_export__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/file_export */ "./public/app/core/utils/file_export.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");



var ExportDataModalCtrl = /** @class */ (function () {
    /** @ngInject */
    function ExportDataModalCtrl(dashboardSrv) {
        this.dashboardSrv = dashboardSrv;
        this.asRows = true;
        this.dateTimeFormat = 'YYYY-MM-DDTHH:mm:ssZ';
        this.excel = false;
    }
    ExportDataModalCtrl.prototype.export = function () {
        var timezone = this.dashboardSrv.getCurrent().timezone;
        var options = {
            excel: this.excel,
            dateTimeFormat: this.dateTimeFormat,
            timezone: timezone,
        };
        if (this.panel === 'table') {
            app_core_utils_file_export__WEBPACK_IMPORTED_MODULE_1__["exportTableDataToCsv"](this.data, this.excel);
        }
        else {
            if (this.asRows) {
                app_core_utils_file_export__WEBPACK_IMPORTED_MODULE_1__["exportSeriesListToCsv"](this.data, options);
            }
            else {
                app_core_utils_file_export__WEBPACK_IMPORTED_MODULE_1__["exportSeriesListToCsvColumns"](this.data, options);
            }
        }
        this.dismiss();
    };
    ExportDataModalCtrl.prototype.dismiss = function () {
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('hide-modal');
    };
    return ExportDataModalCtrl;
}());

function exportDataModal() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/ExportDataModal/template.html',
        controller: ExportDataModalCtrl,
        controllerAs: 'ctrl',
        scope: {
            panel: '<',
            data: '<',
        },
        bindToController: true,
    };
}
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives').directive('exportDataModal', exportDataModal);


/***/ }),

/***/ "./public/app/features/dashboard/components/ExportDataModal/index.ts":
/*!***************************************************************************!*\
  !*** ./public/app/features/dashboard/components/ExportDataModal/index.ts ***!
  \***************************************************************************/
/*! exports provided: ExportDataModalCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ExportDataModalCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ExportDataModalCtrl */ "./public/app/features/dashboard/components/ExportDataModal/ExportDataModalCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExportDataModalCtrl", function() { return _ExportDataModalCtrl__WEBPACK_IMPORTED_MODULE_0__["ExportDataModalCtrl"]; });




/***/ }),

/***/ "./public/app/features/dashboard/components/FolderPicker/FolderPickerCtrl.ts":
/*!***********************************************************************************!*\
  !*** ./public/app/features/dashboard/components/FolderPicker/FolderPickerCtrl.ts ***!
  \***********************************************************************************/
/*! exports provided: FolderPickerCtrl, folderPicker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FolderPickerCtrl", function() { return FolderPickerCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "folderPicker", function() { return folderPicker; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");



var FolderPickerCtrl = /** @class */ (function () {
    /** @ngInject */
    function FolderPickerCtrl(backendSrv, validationSrv, contextSrv) {
        this.backendSrv = backendSrv;
        this.validationSrv = validationSrv;
        this.contextSrv = contextSrv;
        this.rootName = 'General';
        this.isEditor = this.contextSrv.isEditor;
        if (!this.labelClass) {
            this.labelClass = 'width-7';
        }
        this.loadInitialValue();
    }
    FolderPickerCtrl.prototype.getOptions = function (query) {
        var _this = this;
        var params = {
            query: query,
            type: 'dash-folder',
            permission: 'Edit',
        };
        return this.backendSrv.get('api/search', params).then(function (result) {
            if (_this.isEditor &&
                (query === '' ||
                    query.toLowerCase() === 'g' ||
                    query.toLowerCase() === 'ge' ||
                    query.toLowerCase() === 'gen' ||
                    query.toLowerCase() === 'gene' ||
                    query.toLowerCase() === 'gener' ||
                    query.toLowerCase() === 'genera' ||
                    query.toLowerCase() === 'general')) {
                result.unshift({ title: _this.rootName, id: 0 });
            }
            if (_this.isEditor && _this.enableCreateNew && query === '') {
                result.unshift({ title: '-- New Folder --', id: -1 });
            }
            if (_this.enableReset && query === '' && _this.initialTitle !== '') {
                result.unshift({ title: _this.initialTitle, id: null });
            }
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(result, function (item) {
                return { text: item.title, value: item.id };
            });
        });
    };
    FolderPickerCtrl.prototype.onFolderChange = function (option) {
        if (!option) {
            option = { value: 0, text: this.rootName };
        }
        else if (option.value === -1) {
            this.createNewFolder = true;
            this.enterFolderCreation();
            return;
        }
        this.onChange({ $folder: { id: option.value, title: option.text } });
    };
    FolderPickerCtrl.prototype.newFolderNameChanged = function () {
        var _this = this;
        this.newFolderNameTouched = true;
        this.validationSrv
            .validateNewFolderName(this.newFolderName)
            .then(function () {
            _this.hasValidationError = false;
        })
            .catch(function (err) {
            _this.hasValidationError = true;
            _this.validationError = err.message;
        });
    };
    FolderPickerCtrl.prototype.createFolder = function (evt) {
        var _this = this;
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
        return this.backendSrv.createFolder({ title: this.newFolderName }).then(function (result) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('alert-success', ['Folder Created', 'OK']);
            _this.closeCreateFolder();
            _this.folder = { text: result.title, value: result.id };
            _this.onFolderChange(_this.folder);
        });
    };
    FolderPickerCtrl.prototype.cancelCreateFolder = function (evt) {
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
        this.closeCreateFolder();
        this.loadInitialValue();
    };
    FolderPickerCtrl.prototype.closeCreateFolder = function () {
        this.exitFolderCreation();
        this.createNewFolder = false;
        this.hasValidationError = false;
        this.validationError = null;
        this.newFolderName = '';
        this.newFolderNameTouched = false;
    };
    FolderPickerCtrl.prototype.loadInitialValue = function () {
        var _this = this;
        var resetFolder = { text: this.initialTitle, value: null };
        var rootFolder = { text: this.rootName, value: 0 };
        this.getOptions('').then(function (result) {
            var folder;
            if (_this.initialFolderId) {
                // @ts-ignore
                folder = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(result, { value: _this.initialFolderId });
            }
            else if (_this.enableReset && _this.initialTitle && _this.initialFolderId === null) {
                folder = resetFolder;
            }
            if (!folder) {
                if (_this.isEditor) {
                    folder = rootFolder;
                }
                else {
                    // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard
                    var isPersistedDashBoard = _this.dashboardId ? true : false;
                    if (isPersistedDashBoard) {
                        folder = resetFolder;
                    }
                    else {
                        folder = result.length > 0 ? result[0] : resetFolder;
                    }
                }
            }
            _this.folder = folder;
            // if this is not the same as our initial value notify parent
            if (_this.folder.value !== _this.initialFolderId) {
                _this.onChange({ $folder: { id: _this.folder.value, title: _this.folder.text } });
            }
        });
    };
    return FolderPickerCtrl;
}());

function folderPicker() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/FolderPicker/template.html',
        controller: FolderPickerCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            initialTitle: '<',
            initialFolderId: '<',
            labelClass: '@',
            rootName: '@',
            onChange: '&',
            onCreateFolder: '&',
            enterFolderCreation: '&',
            exitFolderCreation: '&',
            enableCreateNew: '@',
            enableReset: '@',
            dashboardId: '<?',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('folderPicker', folderPicker);


/***/ }),

/***/ "./public/app/features/dashboard/components/FolderPicker/index.ts":
/*!************************************************************************!*\
  !*** ./public/app/features/dashboard/components/FolderPicker/index.ts ***!
  \************************************************************************/
/*! exports provided: FolderPickerCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _FolderPickerCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./FolderPickerCtrl */ "./public/app/features/dashboard/components/FolderPicker/FolderPickerCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FolderPickerCtrl", function() { return _FolderPickerCtrl__WEBPACK_IMPORTED_MODULE_0__["FolderPickerCtrl"]; });




/***/ }),

/***/ "./public/app/features/dashboard/components/RowOptions/RowOptionsCtrl.ts":
/*!*******************************************************************************!*\
  !*** ./public/app/features/dashboard/components/RowOptions/RowOptionsCtrl.ts ***!
  \*******************************************************************************/
/*! exports provided: RowOptionsCtrl, rowOptionsDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RowOptionsCtrl", function() { return RowOptionsCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rowOptionsDirective", function() { return rowOptionsDirective; });
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");

var RowOptionsCtrl = /** @class */ (function () {
    /** @ngInject */
    function RowOptionsCtrl() {
        this.source = this.row;
        this.row = this.row.getSaveModel();
    }
    RowOptionsCtrl.prototype.update = function () {
        this.source.title = this.row.title;
        this.source.repeat = this.row.repeat;
        this.onUpdated();
        this.dismiss();
    };
    return RowOptionsCtrl;
}());

function rowOptionsDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/RowOptions/template.html',
        controller: RowOptionsCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            row: '=',
            dismiss: '&',
            onUpdated: '&',
        },
    };
}
app_core_core__WEBPACK_IMPORTED_MODULE_0__["coreModule"].directive('rowOptions', rowOptionsDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/RowOptions/index.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/components/RowOptions/index.ts ***!
  \**********************************************************************/
/*! exports provided: RowOptionsCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _RowOptionsCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./RowOptionsCtrl */ "./public/app/features/dashboard/components/RowOptions/RowOptionsCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RowOptionsCtrl", function() { return _RowOptionsCtrl__WEBPACK_IMPORTED_MODULE_0__["RowOptionsCtrl"]; });




/***/ }),

/***/ "./public/app/features/dashboard/components/SaveModals/SaveDashboardAsModalCtrl.ts":
/*!*****************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/SaveModals/SaveDashboardAsModalCtrl.ts ***!
  \*****************************************************************************************/
/*! exports provided: SaveDashboardAsModalCtrl, saveDashboardAsDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SaveDashboardAsModalCtrl", function() { return SaveDashboardAsModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveDashboardAsDirective", function() { return saveDashboardAsDirective; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var template = "\n<div class=\"modal-body\">\n\t<div class=\"modal-header\">\n\t\t<h2 class=\"modal-header-title\">\n\t\t\t<i class=\"fa fa-copy\"></i>\n\t\t\t<span class=\"p-l-1\">Save As...</span>\n\t\t</h2>\n\n\t\t<a class=\"modal-header-close\" ng-click=\"ctrl.dismiss();\">\n\t\t\t<i class=\"fa fa-remove\"></i>\n\t\t</a>\n\t</div>\n\n\t<form name=\"ctrl.saveForm\" class=\"modal-content\" novalidate>\n\t\t<div class=\"p-t-2\">\n\t\t\t<div class=\"gf-form\">\n\t\t\t\t<label class=\"gf-form-label width-8\">New name</label>\n\t\t\t\t<input type=\"text\" class=\"gf-form-input\" ng-model=\"ctrl.clone.title\" give-focus=\"true\" required aria-label=\"Save dashboard title field\">\n\t\t\t</div>\n      <folder-picker initial-folder-id=\"ctrl.folderId\"\n                       on-change=\"ctrl.onFolderChange($folder)\"\n                       enter-folder-creation=\"ctrl.onEnterFolderCreation()\"\n                       exit-folder-creation=\"ctrl.onExitFolderCreation()\"\n                       enable-create-new=\"true\"\n                       label-class=\"width-8\"\n                       dashboard-id=\"ctrl.clone.id\">\n      </folder-picker>\n      <div class=\"gf-form-inline\">\n        <gf-form-switch class=\"gf-form\" label=\"Copy tags\" label-class=\"width-8\" checked=\"ctrl.copyTags\">\n        </gf-form-switch>\n      </div>\n\t\t</div>\n\n\t\t<div class=\"gf-form-button-row text-center\">\n      <button\n        type=\"submit\"\n        class=\"btn btn-primary\"\n        ng-click=\"ctrl.save()\"\n        ng-disabled=\"!ctrl.isValidFolderSelection\"\n        aria-label=\"Save dashboard button\">\n        Save\n      </button>\n\t\t\t<a class=\"btn-text\" ng-click=\"ctrl.dismiss();\">Cancel</a>\n\t\t</div>\n\t</form>\n</div>\n";
var SaveDashboardAsModalCtrl = /** @class */ (function () {
    /** @ngInject */
    function SaveDashboardAsModalCtrl(dashboardSrv) {
        this.dashboardSrv = dashboardSrv;
        this.isValidFolderSelection = true;
        var dashboard = this.dashboardSrv.getCurrent();
        this.clone = dashboard.getSaveModelClone();
        this.clone.id = null;
        this.clone.uid = '';
        this.clone.title += ' Copy';
        this.clone.editable = true;
        this.clone.hideControls = false;
        this.folderId = dashboard.meta.folderId;
        this.copyTags = false;
        // remove alerts if source dashboard is already persisted
        // do not want to create alert dupes
        if (dashboard.id > 0) {
            this.clone.panels.forEach(function (panel) {
                if (panel.type === 'graph' && panel.alert) {
                    delete panel.thresholds;
                }
                delete panel.alert;
            });
        }
        delete this.clone.autoUpdate;
    }
    SaveDashboardAsModalCtrl.prototype.save = function () {
        if (!this.copyTags) {
            this.clone.tags = [];
        }
        return this.dashboardSrv.save(this.clone, { folderId: this.folderId }).then(this.dismiss);
    };
    SaveDashboardAsModalCtrl.prototype.keyDown = function (evt) {
        if (evt.keyCode === 13) {
            this.save();
        }
    };
    SaveDashboardAsModalCtrl.prototype.onFolderChange = function (folder) {
        this.folderId = folder.id;
    };
    SaveDashboardAsModalCtrl.prototype.onEnterFolderCreation = function () {
        this.isValidFolderSelection = false;
    };
    SaveDashboardAsModalCtrl.prototype.onExitFolderCreation = function () {
        this.isValidFolderSelection = true;
    };
    return SaveDashboardAsModalCtrl;
}());

function saveDashboardAsDirective() {
    return {
        restrict: 'E',
        template: template,
        controller: SaveDashboardAsModalCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: { dismiss: '&' },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('saveDashboardAsModal', saveDashboardAsDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/SaveModals/SaveDashboardModalCtrl.ts":
/*!***************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/SaveModals/SaveDashboardModalCtrl.ts ***!
  \***************************************************************************************/
/*! exports provided: SaveDashboardModalCtrl, saveDashboardModalDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SaveDashboardModalCtrl", function() { return SaveDashboardModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveDashboardModalDirective", function() { return saveDashboardModalDirective; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var template = "\n<div class=\"modal-body\">\n  <div class=\"modal-header\">\n    <h2 class=\"modal-header-title\">\n      <i class=\"fa fa-save\"></i>\n      <span class=\"p-l-1\">Save changes</span>\n    </h2>\n\n    <a class=\"modal-header-close\" ng-click=\"ctrl.dismiss();\">\n      <i class=\"fa fa-remove\"></i>\n    </a>\n  </div>\n\n  <form name=\"ctrl.saveForm\" ng-submit=\"ctrl.save()\" class=\"modal-content\" novalidate>\n    <div class=\"p-t-1\">\n      <div class=\"gf-form-group\" ng-if=\"ctrl.timeChange || ctrl.variableValueChange\">\n\t\t    <gf-form-switch class=\"gf-form\"\n\t\t\t    label=\"Save current time range\" ng-if=\"ctrl.timeChange\" label-class=\"width-12\" switch-class=\"max-width-6\"\n\t\t\t    checked=\"ctrl.saveTimerange\" on-change=\"buildUrl()\">\n\t\t    </gf-form-switch>\n\t\t    <gf-form-switch class=\"gf-form\"\n\t\t\t    label=\"Save current variables\" ng-if=\"ctrl.variableValueChange\" label-class=\"width-12\" switch-class=\"max-width-6\"\n\t\t\t    checked=\"ctrl.saveVariables\" on-change=\"buildUrl()\">\n\t\t    </gf-form-switch>\n\t    </div>\n      <div class=\"gf-form\">\n        <label class=\"gf-form-hint\">\n          <input\n            type=\"text\"\n            name=\"message\"\n            class=\"gf-form-input\"\n            placeholder=\"Add a note to describe your changes &hellip;\"\n            give-focus=\"true\"\n            ng-model=\"ctrl.message\"\n            ng-model-options=\"{allowInvalid: true}\"\n            ng-maxlength=\"this.max\"\n            maxlength=\"64\"\n            autocomplete=\"off\" />\n          <small class=\"gf-form-hint-text muted\" ng-cloak>\n            <span ng-class=\"{'text-error': ctrl.saveForm.message.$invalid && ctrl.saveForm.message.$dirty }\">\n              {{ctrl.message.length || 0}}\n            </span>\n            / {{ctrl.max}} characters\n          </small>\n        </label>\n      </div>\n    </div>\n\n    <div class=\"gf-form-button-row text-center\">\n      <button\n        id=\"saveBtn\"\n        type=\"submit\"\n        class=\"btn btn-primary\"\n        ng-class=\"{'btn-primary--processing': ctrl.isSaving}\"\n        ng-disabled=\"ctrl.saveForm.$invalid || ctrl.isSaving\"\n      >\n        <span ng-if=\"!ctrl.isSaving\">Save</span>\n        <span ng-if=\"ctrl.isSaving === true\">Saving...</span>\n      </button>\n      <button class=\"btn btn-inverse\" ng-click=\"ctrl.dismiss();\">Cancel</button>\n    </div>\n  </form>\n</div>\n";
var SaveDashboardModalCtrl = /** @class */ (function () {
    /** @ngInject */
    function SaveDashboardModalCtrl(dashboardSrv) {
        this.dashboardSrv = dashboardSrv;
        this.saveVariables = false;
        this.saveTimerange = false;
        this.current = [];
        this.originalCurrent = [];
        this.timeChange = false;
        this.variableValueChange = false;
        this.message = '';
        this.max = 64;
        this.isSaving = false;
        this.timeChange = this.dashboardSrv.getCurrent().hasTimeChanged();
        this.variableValueChange = this.dashboardSrv.getCurrent().hasVariableValuesChanged();
    }
    SaveDashboardModalCtrl.prototype.save = function () {
        if (!this.saveForm.$valid) {
            return;
        }
        var options = {
            saveVariables: this.saveVariables,
            saveTimerange: this.saveTimerange,
            message: this.message,
        };
        var dashboard = this.dashboardSrv.getCurrent();
        var saveModel = dashboard.getSaveModelClone(options);
        this.isSaving = true;
        return this.dashboardSrv.save(saveModel, options).then(this.postSave.bind(this, options));
    };
    SaveDashboardModalCtrl.prototype.postSave = function (options) {
        if (options.saveVariables) {
            this.dashboardSrv.getCurrent().resetOriginalVariables();
        }
        if (options.saveTimerange) {
            this.dashboardSrv.getCurrent().resetOriginalTime();
        }
        this.dismiss();
    };
    return SaveDashboardModalCtrl;
}());

function saveDashboardModalDirective() {
    return {
        restrict: 'E',
        template: template,
        controller: SaveDashboardModalCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: { dismiss: '&' },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('saveDashboardModal', saveDashboardModalDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/SaveModals/SaveProvisionedDashboardModalCtrl.ts":
/*!**************************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/SaveModals/SaveProvisionedDashboardModalCtrl.ts ***!
  \**************************************************************************************************/
/*! exports provided: SaveProvisionedDashboardModalCtrl, saveProvisionedDashboardModalDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SaveProvisionedDashboardModalCtrl", function() { return SaveProvisionedDashboardModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveProvisionedDashboardModalDirective", function() { return saveProvisionedDashboardModalDirective; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! file-saver */ "./node_modules/file-saver/FileSaver.js");
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");



var template = "\n<div class=\"modal-body\">\n  <div class=\"modal-header\">\n    <h2 class=\"modal-header-title\">\n      <i class=\"fa fa-save\"></i><span class=\"p-l-1\">Cannot save provisioned dashboard</span>\n    </h2>\n\n    <a class=\"modal-header-close\" ng-click=\"ctrl.dismiss();\">\n      <i class=\"fa fa-remove\"></i>\n    </a>\n  </div>\n\n  <div class=\"modal-content\">\n    <small>\n      This dashboard cannot be saved from Grafana's UI since it has been provisioned from another source.\n      Copy the JSON or save it to a file below. Then you can update your dashboard in corresponding provisioning source.<br/>\n      <i>See <a class=\"external-link\" href=\"http://docs.grafana.org/administration/provisioning/#dashboards\" target=\"_blank\">\n      documentation</a> for more information about provisioning.</i>\n    </small>\n    <div class=\"p-t-1\">\n      File path: {{ctrl.dashboardModel.meta.provisionedExternalId}}\n    </div>\n    <div class=\"p-t-2\">\n      <div class=\"gf-form\">\n        <code-editor content=\"ctrl.dashboardJson\" data-mode=\"json\" data-max-lines=15></code-editor>\n      </div>\n      <div class=\"gf-form-button-row\">\n        <button class=\"btn btn-primary\" clipboard-button=\"ctrl.getJsonForClipboard()\">\n          Copy JSON to Clipboard\n        </button>\n        <button class=\"btn btn-secondary\" clipboard-button=\"ctrl.save()\">\n          Save JSON to file\n        </button>\n        <a class=\"btn btn-link\" ng-click=\"ctrl.dismiss();\">Cancel</a>\n      </div>\n    </div>\n  </div>\n</div>\n";
var SaveProvisionedDashboardModalCtrl = /** @class */ (function () {
    /** @ngInject */
    function SaveProvisionedDashboardModalCtrl(dashboardSrv) {
        this.dashboardModel = dashboardSrv.getCurrent();
        this.dash = this.dashboardModel.getSaveModelClone();
        delete this.dash.id;
        this.dashboardJson = angular__WEBPACK_IMPORTED_MODULE_0___default.a.toJson(this.dash, true);
    }
    SaveProvisionedDashboardModalCtrl.prototype.save = function () {
        var blob = new Blob([angular__WEBPACK_IMPORTED_MODULE_0___default.a.toJson(this.dash, true)], {
            type: 'application/json;charset=utf-8',
        });
        Object(file_saver__WEBPACK_IMPORTED_MODULE_1__["saveAs"])(blob, this.dash.title + '-' + new Date().getTime() + '.json');
    };
    SaveProvisionedDashboardModalCtrl.prototype.getJsonForClipboard = function () {
        return this.dashboardJson;
    };
    return SaveProvisionedDashboardModalCtrl;
}());

function saveProvisionedDashboardModalDirective() {
    return {
        restrict: 'E',
        template: template,
        controller: SaveProvisionedDashboardModalCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: { dismiss: '&' },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].directive('saveProvisionedDashboardModal', saveProvisionedDashboardModalDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/SaveModals/index.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/components/SaveModals/index.ts ***!
  \**********************************************************************/
/*! exports provided: SaveDashboardAsModalCtrl, SaveDashboardModalCtrl, SaveProvisionedDashboardModalCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _SaveDashboardAsModalCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SaveDashboardAsModalCtrl */ "./public/app/features/dashboard/components/SaveModals/SaveDashboardAsModalCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SaveDashboardAsModalCtrl", function() { return _SaveDashboardAsModalCtrl__WEBPACK_IMPORTED_MODULE_0__["SaveDashboardAsModalCtrl"]; });

/* harmony import */ var _SaveDashboardModalCtrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SaveDashboardModalCtrl */ "./public/app/features/dashboard/components/SaveModals/SaveDashboardModalCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SaveDashboardModalCtrl", function() { return _SaveDashboardModalCtrl__WEBPACK_IMPORTED_MODULE_1__["SaveDashboardModalCtrl"]; });

/* harmony import */ var _SaveProvisionedDashboardModalCtrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SaveProvisionedDashboardModalCtrl */ "./public/app/features/dashboard/components/SaveModals/SaveProvisionedDashboardModalCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SaveProvisionedDashboardModalCtrl", function() { return _SaveProvisionedDashboardModalCtrl__WEBPACK_IMPORTED_MODULE_2__["SaveProvisionedDashboardModalCtrl"]; });






/***/ }),

/***/ "./public/app/features/dashboard/components/ShareModal/ShareModalCtrl.ts":
/*!*******************************************************************************!*\
  !*** ./public/app/features/dashboard/components/ShareModal/ShareModalCtrl.ts ***!
  \*******************************************************************************/
/*! exports provided: ShareModalCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShareModalCtrl", function() { return ShareModalCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/url */ "./public/app/core/utils/url.ts");




/** @ngInject */
function ShareModalCtrl($scope, $rootScope, $location, $timeout, timeSrv, templateSrv, linkSrv) {
    $scope.options = {
        forCurrent: true,
        includeTemplateVars: true,
        theme: 'current',
    };
    $scope.editor = { index: $scope.tabIndex || 0 };
    $scope.init = function () {
        $scope.panel = $scope.model && $scope.model.panel ? $scope.model.panel : $scope.panel; // React pass panel and dashboard in the "model" property
        $scope.dashboard = $scope.model && $scope.model.dashboard ? $scope.model.dashboard : $scope.dashboard; // ^
        $scope.modeSharePanel = $scope.panel ? true : false;
        $scope.tabs = [{ title: 'Link', src: 'shareLink.html' }];
        if ($scope.modeSharePanel) {
            $scope.modalTitle = 'Share Panel';
            $scope.tabs.push({ title: 'Embed', src: 'shareEmbed.html' });
        }
        else {
            $scope.modalTitle = 'Share';
        }
        if (!$scope.dashboard.meta.isSnapshot) {
            $scope.tabs.push({ title: 'Snapshot', src: 'shareSnapshot.html' });
        }
        if (!$scope.dashboard.meta.isSnapshot && !$scope.modeSharePanel) {
            $scope.tabs.push({ title: 'Export', src: 'shareExport.html' });
        }
        $scope.buildUrl();
    };
    $scope.buildUrl = function () {
        var baseUrl = $location.absUrl();
        var queryStart = baseUrl.indexOf('?');
        if (queryStart !== -1) {
            baseUrl = baseUrl.substring(0, queryStart);
        }
        var params = angular__WEBPACK_IMPORTED_MODULE_0___default.a.copy($location.search());
        var range = timeSrv.timeRange();
        params.from = range.from.valueOf();
        params.to = range.to.valueOf();
        params.orgId = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].bootData.user.orgId;
        if ($scope.options.includeTemplateVars) {
            templateSrv.fillVariableValuesForUrl(params);
        }
        if (!$scope.options.forCurrent) {
            delete params.from;
            delete params.to;
        }
        if ($scope.options.theme !== 'current') {
            params.theme = $scope.options.theme;
        }
        if ($scope.modeSharePanel) {
            params.panelId = $scope.panel.id;
            params.fullscreen = true;
        }
        else {
            delete params.panelId;
            delete params.fullscreen;
        }
        $scope.shareUrl = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["appendQueryToUrl"])(baseUrl, Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["toUrlParams"])(params));
        var soloUrl = baseUrl.replace(app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/dashboard/', app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/dashboard-solo/');
        soloUrl = soloUrl.replace(app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/d/', app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/d-solo/');
        delete params.fullscreen;
        delete params.edit;
        soloUrl = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["appendQueryToUrl"])(soloUrl, Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["toUrlParams"])(params));
        $scope.iframeHtml = '<iframe src="' + soloUrl + '" width="450" height="200" frameborder="0"></iframe>';
        $scope.imageUrl = soloUrl.replace(app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/dashboard-solo/', app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/render/dashboard-solo/');
        $scope.imageUrl = $scope.imageUrl.replace(app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/d-solo/', app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/render/d-solo/');
        $scope.imageUrl += '&width=1000&height=500' + $scope.getLocalTimeZone();
    };
    // This function will try to return the proper full name of the local timezone
    // Chrome does not handle the timezone offset (but phantomjs does)
    $scope.getLocalTimeZone = function () {
        var utcOffset = '&tz=UTC' + encodeURIComponent(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])().format('Z'));
        // Older browser does not the internationalization API
        if (!window.Intl) {
            return utcOffset;
        }
        var dateFormat = window.Intl.DateTimeFormat();
        if (!dateFormat.resolvedOptions) {
            return utcOffset;
        }
        var options = dateFormat.resolvedOptions();
        if (!options.timeZone) {
            return utcOffset;
        }
        return '&tz=' + encodeURIComponent(options.timeZone);
    };
    $scope.getShareUrl = function () {
        return $scope.shareUrl;
    };
}
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.controllers').controller('ShareModalCtrl', ShareModalCtrl);


/***/ }),

/***/ "./public/app/features/dashboard/components/ShareModal/ShareSnapshotCtrl.ts":
/*!**********************************************************************************!*\
  !*** ./public/app/features/dashboard/components/ShareModal/ShareSnapshotCtrl.ts ***!
  \**********************************************************************************/
/*! exports provided: ShareSnapshotCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShareSnapshotCtrl", function() { return ShareSnapshotCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


var ShareSnapshotCtrl = /** @class */ (function () {
    /** @ngInject */
    function ShareSnapshotCtrl($scope, $rootScope, $location, backendSrv, $timeout, timeSrv) {
        $scope.snapshot = {
            name: $scope.dashboard.title,
            expires: 0,
            timeoutSeconds: 4,
        };
        $scope.step = 1;
        $scope.expireOptions = [
            { text: '1 Hour', value: 60 * 60 },
            { text: '1 Day', value: 60 * 60 * 24 },
            { text: '7 Days', value: 60 * 60 * 24 * 7 },
            { text: 'Never', value: 0 },
        ];
        $scope.accessOptions = [
            { text: 'Anyone with the link', value: 1 },
            { text: 'Organization users', value: 2 },
            { text: 'Public on the web', value: 3 },
        ];
        $scope.init = function () {
            backendSrv.get('/api/snapshot/shared-options').then(function (options) {
                $scope.sharingButtonText = options['externalSnapshotName'];
                $scope.externalEnabled = options['externalEnabled'];
            });
        };
        $scope.apiUrl = '/api/snapshots';
        $scope.createSnapshot = function (external) {
            $scope.dashboard.snapshot = {
                timestamp: new Date(),
            };
            if (!external) {
                $scope.dashboard.snapshot.originalUrl = $location.absUrl();
            }
            $scope.loading = true;
            $scope.snapshot.external = external;
            $scope.dashboard.startRefresh();
            $timeout(function () {
                $scope.saveSnapshot(external);
            }, $scope.snapshot.timeoutSeconds * 1000);
        };
        $scope.saveSnapshot = function (external) {
            var dash = $scope.dashboard.getSaveModelClone();
            $scope.scrubDashboard(dash);
            var cmdData = {
                dashboard: dash,
                name: dash.title,
                expires: $scope.snapshot.expires,
                external: external,
            };
            backendSrv.post($scope.apiUrl, cmdData).then(function (results) {
                $scope.loading = false;
                $scope.deleteUrl = results.deleteUrl;
                $scope.snapshotUrl = results.url;
                $scope.step = 2;
            }, function () {
                $scope.loading = false;
            });
        };
        $scope.getSnapshotUrl = function () {
            return $scope.snapshotUrl;
        };
        $scope.scrubDashboard = function (dash) {
            // change title
            dash.title = $scope.snapshot.name;
            // make relative times absolute
            dash.time = timeSrv.timeRange();
            // remove panel queries & links
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(dash.panels, function (panel) {
                panel.targets = [];
                panel.links = [];
                panel.datasource = null;
            });
            // remove annotation queries
            dash.annotations.list = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.chain(dash.annotations.list)
                .filter(function (annotation) {
                return annotation.enable;
            })
                .map(function (annotation) {
                return {
                    name: annotation.name,
                    enable: annotation.enable,
                    iconColor: annotation.iconColor,
                    snapshotData: annotation.snapshotData,
                    type: annotation.type,
                    builtIn: annotation.builtIn,
                    hide: annotation.hide,
                };
            })
                .value();
            // remove template queries
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(dash.templating.list, function (variable) {
                variable.query = '';
                variable.options = variable.current;
                variable.refresh = false;
            });
            // snapshot single panel
            if ($scope.modeSharePanel) {
                var singlePanel = $scope.panel.getSaveModel();
                singlePanel.gridPos.w = 24;
                singlePanel.gridPos.x = 0;
                singlePanel.gridPos.y = 0;
                singlePanel.gridPos.h = 20;
                dash.panels = [singlePanel];
            }
            // cleanup snapshotData
            delete $scope.dashboard.snapshot;
            $scope.dashboard.forEachPanel(function (panel) {
                delete panel.snapshotData;
            });
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each($scope.dashboard.annotations.list, function (annotation) {
                delete annotation.snapshotData;
            });
        };
        $scope.deleteSnapshot = function () {
            backendSrv.get($scope.deleteUrl).then(function () {
                $scope.step = 3;
            });
        };
    }
    return ShareSnapshotCtrl;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.controllers').controller('ShareSnapshotCtrl', ShareSnapshotCtrl);


/***/ }),

/***/ "./public/app/features/dashboard/components/ShareModal/index.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/components/ShareModal/index.ts ***!
  \**********************************************************************/
/*! exports provided: ShareModalCtrl, ShareSnapshotCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ShareModalCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ShareModalCtrl */ "./public/app/features/dashboard/components/ShareModal/ShareModalCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShareModalCtrl", function() { return _ShareModalCtrl__WEBPACK_IMPORTED_MODULE_0__["ShareModalCtrl"]; });

/* harmony import */ var _ShareSnapshotCtrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ShareSnapshotCtrl */ "./public/app/features/dashboard/components/ShareModal/ShareSnapshotCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShareSnapshotCtrl", function() { return _ShareSnapshotCtrl__WEBPACK_IMPORTED_MODULE_1__["ShareSnapshotCtrl"]; });





/***/ }),

/***/ "./public/app/features/dashboard/components/SubMenu/SubMenu.tsx":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/components/SubMenu/SubMenu.tsx ***!
  \**********************************************************************/
/*! exports provided: SubMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubMenu", function() { return SubMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");

// Libaries

// Utils & Services

var SubMenu = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SubMenu, _super);
    function SubMenu() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SubMenu.prototype.componentDidMount = function () {
        var loader = Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getAngularLoader"])();
        var template = '<dashboard-submenu dashboard="dashboard" />';
        var scopeProps = { dashboard: this.props.dashboard };
        this.angularCmp = loader.load(this.element, scopeProps, template);
    };
    SubMenu.prototype.componentWillUnmount = function () {
        if (this.angularCmp) {
            this.angularCmp.destroy();
        }
    };
    SubMenu.prototype.render = function () {
        var _this = this;
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: function (element) { return (_this.element = element); } });
    };
    return SubMenu;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/features/dashboard/components/SubMenu/SubMenuCtrl.ts":
/*!*************************************************************************!*\
  !*** ./public/app/features/dashboard/components/SubMenu/SubMenuCtrl.ts ***!
  \*************************************************************************/
/*! exports provided: SubMenuCtrl, submenuDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubMenuCtrl", function() { return SubMenuCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "submenuDirective", function() { return submenuDirective; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


var SubMenuCtrl = /** @class */ (function () {
    /** @ngInject */
    function SubMenuCtrl(variableSrv, $location) {
        this.variableSrv = variableSrv;
        this.$location = $location;
        this.annotations = this.dashboard.templating.list;
        this.variables = this.variableSrv.variables;
    }
    SubMenuCtrl.prototype.annotationStateChanged = function () {
        this.dashboard.startRefresh();
    };
    SubMenuCtrl.prototype.variableUpdated = function (variable) {
        this.variableSrv.variableUpdated(variable, true);
    };
    SubMenuCtrl.prototype.openEditView = function (editview) {
        var search = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.extend(this.$location.search(), { editview: editview });
        this.$location.search(search);
    };
    return SubMenuCtrl;
}());

function submenuDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/SubMenu/template.html',
        controller: SubMenuCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            dashboard: '=',
        },
    };
}
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives').directive('dashboardSubmenu', submenuDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/SubMenu/index.ts":
/*!*******************************************************************!*\
  !*** ./public/app/features/dashboard/components/SubMenu/index.ts ***!
  \*******************************************************************/
/*! exports provided: SubMenuCtrl, SubMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _SubMenuCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SubMenuCtrl */ "./public/app/features/dashboard/components/SubMenu/SubMenuCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubMenuCtrl", function() { return _SubMenuCtrl__WEBPACK_IMPORTED_MODULE_0__["SubMenuCtrl"]; });

/* harmony import */ var _SubMenu__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SubMenu */ "./public/app/features/dashboard/components/SubMenu/SubMenu.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubMenu", function() { return _SubMenu__WEBPACK_IMPORTED_MODULE_1__["SubMenu"]; });





/***/ }),

/***/ "./public/app/features/dashboard/components/UnsavedChangesModal/UnsavedChangesModalCtrl.ts":
/*!*************************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/UnsavedChangesModal/UnsavedChangesModalCtrl.ts ***!
  \*************************************************************************************************/
/*! exports provided: UnsavedChangesModalCtrl, unsavedChangesModalDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsavedChangesModalCtrl", function() { return UnsavedChangesModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unsavedChangesModalDirective", function() { return unsavedChangesModalDirective; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var template = "\n<div class=\"modal-body\">\n  <div class=\"modal-header\">\n    <h2 class=\"modal-header-title\">\n      <i class=\"fa fa-exclamation\"></i>\n      <span class=\"p-l-1\">Unsaved changes</span>\n    </h2>\n\n    <a class=\"modal-header-close\" ng-click=\"ctrl.dismiss();\">\n      <i class=\"fa fa-remove\"></i>\n    </a>\n  </div>\n\n  <div class=\"modal-content text-center\">\n\n    <div class=\"confirm-modal-text\">\n      Do you want to save your changes?\n    </div>\n\n    <div class=\"confirm-modal-buttons\">\n      <button type=\"button\" class=\"btn btn-primary\" ng-click=\"ctrl.save()\">Save</button>\n      <button type=\"button\" class=\"btn btn-danger\" ng-click=\"ctrl.discard()\">Discard</button>\n      <button type=\"button\" class=\"btn btn-inverse\" ng-click=\"ctrl.dismiss()\">Cancel</button>\n    </div>\n  </div>\n</div>\n";
var UnsavedChangesModalCtrl = /** @class */ (function () {
    /** @ngInject */
    function UnsavedChangesModalCtrl(unsavedChangesSrv) {
        this.unsavedChangesSrv = unsavedChangesSrv;
    }
    UnsavedChangesModalCtrl.prototype.discard = function () {
        this.dismiss();
        this.unsavedChangesSrv.tracker.discardChanges();
    };
    UnsavedChangesModalCtrl.prototype.save = function () {
        this.dismiss();
        this.unsavedChangesSrv.tracker.saveChanges();
    };
    return UnsavedChangesModalCtrl;
}());

function unsavedChangesModalDirective() {
    return {
        restrict: 'E',
        template: template,
        controller: UnsavedChangesModalCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: { dismiss: '&' },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('unsavedChangesModal', unsavedChangesModalDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/UnsavedChangesModal/index.ts":
/*!*******************************************************************************!*\
  !*** ./public/app/features/dashboard/components/UnsavedChangesModal/index.ts ***!
  \*******************************************************************************/
/*! exports provided: UnsavedChangesModalCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _UnsavedChangesModalCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./UnsavedChangesModalCtrl */ "./public/app/features/dashboard/components/UnsavedChangesModal/UnsavedChangesModalCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnsavedChangesModalCtrl", function() { return _UnsavedChangesModalCtrl__WEBPACK_IMPORTED_MODULE_0__["UnsavedChangesModalCtrl"]; });




/***/ }),

/***/ "./public/app/features/dashboard/components/VersionHistory/HistoryListCtrl.ts":
/*!************************************************************************************!*\
  !*** ./public/app/features/dashboard/components/VersionHistory/HistoryListCtrl.ts ***!
  \************************************************************************************/
/*! exports provided: HistoryListCtrl, dashboardHistoryDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HistoryListCtrl", function() { return HistoryListCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardHistoryDirective", function() { return dashboardHistoryDirective; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");





var HistoryListCtrl = /** @class */ (function () {
    /** @ngInject */
    function HistoryListCtrl($route, $rootScope, $location, $q, historySrv, $scope) {
        this.$route = $route;
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.$q = $q;
        this.historySrv = historySrv;
        this.$scope = $scope;
        this.appending = false;
        this.diff = 'basic';
        this.limit = 10;
        this.loading = false;
        this.max = 2;
        this.mode = 'list';
        this.start = 0;
        this.canCompare = false;
        this.$rootScope.onAppEvent('dashboard-saved', this.onDashboardSaved.bind(this), $scope);
        this.resetFromSource();
    }
    HistoryListCtrl.prototype.onDashboardSaved = function () {
        this.resetFromSource();
    };
    HistoryListCtrl.prototype.switchMode = function (mode) {
        this.mode = mode;
        if (this.mode === 'list') {
            this.reset();
        }
    };
    HistoryListCtrl.prototype.dismiss = function () {
        this.$rootScope.appEvent('hide-dash-editor');
    };
    HistoryListCtrl.prototype.addToLog = function () {
        this.start = this.start + this.limit;
        this.getLog(true);
    };
    HistoryListCtrl.prototype.revisionSelectionChanged = function () {
        var selected = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.revisions, { checked: true }).length;
        this.canCompare = selected === 2;
    };
    HistoryListCtrl.prototype.formatDate = function (date) {
        return this.dashboard.formatDate(date);
    };
    HistoryListCtrl.prototype.formatBasicDate = function (date) {
        var now = this.dashboard.timezone === 'browser' ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])() : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["toUtc"])();
        var then = this.dashboard.timezone === 'browser' ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(date) : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["toUtc"])(date);
        return then.from(now);
    };
    HistoryListCtrl.prototype.getDiff = function (diff) {
        var _this = this;
        this.diff = diff;
        this.mode = 'compare';
        // have it already been fetched?
        // @ts-ignore
        if (this.delta[this.diff]) {
            // @ts-ignore
            return this.$q.when(this.delta[this.diff]);
        }
        var selected = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(this.revisions, { checked: true });
        this.newInfo = selected[0];
        this.baseInfo = selected[1];
        this.isNewLatest = this.newInfo.version === this.dashboard.version;
        this.loading = true;
        var options = {
            new: {
                dashboardId: this.dashboard.id,
                version: this.newInfo.version,
            },
            base: {
                dashboardId: this.dashboard.id,
                version: this.baseInfo.version,
            },
            diffType: diff,
        };
        return this.historySrv
            .calculateDiff(options)
            .then(function (response) {
            // @ts-ignore
            _this.delta[_this.diff] = response;
        })
            .catch(function () {
            _this.mode = 'list';
        })
            .finally(function () {
            _this.loading = false;
        });
    };
    HistoryListCtrl.prototype.getLog = function (append) {
        var _this = this;
        if (append === void 0) { append = false; }
        this.loading = !append;
        this.appending = append;
        var options = {
            limit: this.limit,
            start: this.start,
        };
        return this.historySrv
            .getHistoryList(this.dashboard, options)
            .then(function (revisions) {
            var e_1, _a;
            try {
                // set formatted dates & default values
                for (var revisions_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](revisions), revisions_1_1 = revisions_1.next(); !revisions_1_1.done; revisions_1_1 = revisions_1.next()) {
                    var rev = revisions_1_1.value;
                    rev.createdDateString = _this.formatDate(rev.created);
                    rev.ageString = _this.formatBasicDate(rev.created);
                    rev.checked = false;
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (revisions_1_1 && !revisions_1_1.done && (_a = revisions_1.return)) _a.call(revisions_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            _this.revisions = append ? _this.revisions.concat(revisions) : revisions;
        })
            .catch(function (err) {
            _this.loading = false;
        })
            .finally(function () {
            _this.loading = false;
            _this.appending = false;
        });
    };
    HistoryListCtrl.prototype.isLastPage = function () {
        return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.revisions, function (rev) { return rev.version === 1; });
    };
    HistoryListCtrl.prototype.reset = function () {
        this.delta = { basic: '', json: '' };
        this.diff = 'basic';
        this.mode = 'list';
        this.revisions = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.revisions, function (rev) { return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.extend({}, rev, { checked: false }); });
        this.canCompare = false;
        this.start = 0;
        this.isNewLatest = false;
    };
    HistoryListCtrl.prototype.resetFromSource = function () {
        this.revisions = [];
        return this.getLog().then(this.reset.bind(this));
    };
    HistoryListCtrl.prototype.restore = function (version) {
        this.$rootScope.appEvent('confirm-modal', {
            title: 'Restore version',
            text: '',
            text2: "Are you sure you want to restore the dashboard to version " + version + "? All unsaved changes will be lost.",
            icon: 'fa-history',
            yesText: "Yes, restore to version " + version,
            onConfirm: this.restoreConfirm.bind(this, version),
        });
    };
    HistoryListCtrl.prototype.restoreConfirm = function (version) {
        var _this = this;
        this.loading = true;
        return this.historySrv
            .restoreDashboard(this.dashboard, version)
            .then(function (response) {
            _this.$location.url(app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__["default"].stripBaseFromUrl(response.url)).replace();
            _this.$route.reload();
            _this.$rootScope.appEvent('alert-success', ['Dashboard restored', 'Restored from version ' + version]);
        })
            .catch(function () {
            _this.mode = 'list';
            _this.loading = false;
        });
    };
    return HistoryListCtrl;
}());

function dashboardHistoryDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/dashboard/components/VersionHistory/template.html',
        controller: HistoryListCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            dashboard: '=',
        },
    };
}
angular__WEBPACK_IMPORTED_MODULE_2___default.a.module('grafana.directives').directive('gfDashboardHistory', dashboardHistoryDirective);


/***/ }),

/***/ "./public/app/features/dashboard/components/VersionHistory/HistorySrv.ts":
/*!*******************************************************************************!*\
  !*** ./public/app/features/dashboard/components/VersionHistory/HistorySrv.ts ***!
  \*******************************************************************************/
/*! exports provided: HistorySrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HistorySrv", function() { return HistorySrv; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");


var HistorySrv = /** @class */ (function () {
    /** @ngInject */
    function HistorySrv(backendSrv) {
        this.backendSrv = backendSrv;
    }
    HistorySrv.prototype.getHistoryList = function (dashboard, options) {
        var id = dashboard && dashboard.id ? dashboard.id : void 0;
        return id ? this.backendSrv.get("api/dashboards/id/" + id + "/versions", options) : Promise.resolve([]);
    };
    HistorySrv.prototype.calculateDiff = function (options) {
        return this.backendSrv.post('api/dashboards/calculate-diff', options);
    };
    HistorySrv.prototype.restoreDashboard = function (dashboard, version) {
        var id = dashboard && dashboard.id ? dashboard.id : void 0;
        var url = "api/dashboards/id/" + id + "/restore";
        return id && lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(version) ? this.backendSrv.post(url, { version: version }) : Promise.resolve({});
    };
    return HistorySrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('historySrv', HistorySrv);


/***/ }),

/***/ "./public/app/features/dashboard/components/VersionHistory/index.ts":
/*!**************************************************************************!*\
  !*** ./public/app/features/dashboard/components/VersionHistory/index.ts ***!
  \**************************************************************************/
/*! exports provided: HistoryListCtrl, HistorySrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _HistoryListCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HistoryListCtrl */ "./public/app/features/dashboard/components/VersionHistory/HistoryListCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HistoryListCtrl", function() { return _HistoryListCtrl__WEBPACK_IMPORTED_MODULE_0__["HistoryListCtrl"]; });

/* harmony import */ var _HistorySrv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./HistorySrv */ "./public/app/features/dashboard/components/VersionHistory/HistorySrv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HistorySrv", function() { return _HistorySrv__WEBPACK_IMPORTED_MODULE_1__["HistorySrv"]; });





/***/ }),

/***/ "./public/app/features/dashboard/dashgrid/PanelPluginError.tsx":
/*!*********************************************************************!*\
  !*** ./public/app/features/dashboard/dashgrid/PanelPluginError.tsx ***!
  \*********************************************************************/
/*! exports provided: getPanelPluginLoadError, getPanelPluginNotFound */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelPluginLoadError", function() { return getPanelPluginLoadError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelPluginNotFound", function() { return getPanelPluginNotFound; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/components/AlertBox/AlertBox */ "./public/app/core/components/AlertBox/AlertBox.tsx");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


// Components

// Types


var PanelPluginError = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PanelPluginError, _super);
    function PanelPluginError(props) {
        return _super.call(this, props) || this;
    }
    PanelPluginError.prototype.render = function () {
        var style = {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100%',
        };
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: style },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_AlertBox_AlertBox__WEBPACK_IMPORTED_MODULE_2__["AlertBox"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ severity: app_types__WEBPACK_IMPORTED_MODULE_3__["AppNotificationSeverity"].Error }, this.props))));
    };
    return PanelPluginError;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
function getPanelPluginLoadError(meta, err) {
    var LoadError = /** @class */ (function (_super) {
        tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LoadError, _super);
        function LoadError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LoadError.prototype.render = function () {
            var text = (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                "Check the server startup logs for more information. ",
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                "If this plugin was loaded from git, make sure it was compiled."));
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(PanelPluginError, { title: "Error loading: " + meta.id, text: text });
        };
        return LoadError;
    }(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
    var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_4__["PanelPlugin"](LoadError);
    plugin.meta = meta;
    plugin.loadError = true;
    return plugin;
}
function getPanelPluginNotFound(id) {
    var NotFound = /** @class */ (function (_super) {
        tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NotFound, _super);
        function NotFound() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        NotFound.prototype.render = function () {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(PanelPluginError, { title: "Panel plugin not found: " + id });
        };
        return NotFound;
    }(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
    var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_4__["PanelPlugin"](NotFound);
    plugin.meta = {
        id: id,
        name: id,
        sort: 100,
        type: _grafana_ui__WEBPACK_IMPORTED_MODULE_4__["PluginType"].panel,
        module: '',
        baseUrl: '',
        info: {
            author: {
                name: '',
            },
            description: '',
            links: [],
            logos: {
                large: '',
                small: '',
            },
            screenshots: [],
            updated: '',
            version: '',
        },
    };
    return plugin;
}


/***/ }),

/***/ "./public/app/features/dashboard/index.ts":
/*!************************************************!*\
  !*** ./public/app/features/dashboard/index.ts ***!
  \************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _services_UnsavedChangesSrv__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./services/UnsavedChangesSrv */ "./public/app/features/dashboard/services/UnsavedChangesSrv.ts");
/* harmony import */ var _services_DashboardLoaderSrv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./services/DashboardLoaderSrv */ "./public/app/features/dashboard/services/DashboardLoaderSrv.ts");
/* harmony import */ var _services_DashboardSrv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./services/DashboardSrv */ "./public/app/features/dashboard/services/DashboardSrv.ts");
/* harmony import */ var _components_DashLinks__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/DashLinks */ "./public/app/features/dashboard/components/DashLinks/index.ts");
/* harmony import */ var _components_DashExportModal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./components/DashExportModal */ "./public/app/features/dashboard/components/DashExportModal/index.ts");
/* harmony import */ var _components_DashNav__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./components/DashNav */ "./public/app/features/dashboard/components/DashNav/index.ts");
/* harmony import */ var _components_ExportDataModal__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./components/ExportDataModal */ "./public/app/features/dashboard/components/ExportDataModal/index.ts");
/* harmony import */ var _components_FolderPicker__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./components/FolderPicker */ "./public/app/features/dashboard/components/FolderPicker/index.ts");
/* harmony import */ var _components_VersionHistory__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./components/VersionHistory */ "./public/app/features/dashboard/components/VersionHistory/index.ts");
/* harmony import */ var _components_DashboardSettings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./components/DashboardSettings */ "./public/app/features/dashboard/components/DashboardSettings/index.ts");
/* harmony import */ var _components_SubMenu__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./components/SubMenu */ "./public/app/features/dashboard/components/SubMenu/index.ts");
/* harmony import */ var _components_UnsavedChangesModal__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./components/UnsavedChangesModal */ "./public/app/features/dashboard/components/UnsavedChangesModal/index.ts");
/* harmony import */ var _components_SaveModals__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./components/SaveModals */ "./public/app/features/dashboard/components/SaveModals/index.ts");
/* harmony import */ var _components_ShareModal__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./components/ShareModal */ "./public/app/features/dashboard/components/ShareModal/index.ts");
/* harmony import */ var _components_AdHocFilters__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./components/AdHocFilters */ "./public/app/features/dashboard/components/AdHocFilters/index.ts");
/* harmony import */ var _components_RowOptions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./components/RowOptions */ "./public/app/features/dashboard/components/RowOptions/index.ts");
/* harmony import */ var _components_DashboardPermissions_DashboardPermissions__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./components/DashboardPermissions/DashboardPermissions */ "./public/app/features/dashboard/components/DashboardPermissions/DashboardPermissions.tsx");
/* harmony import */ var app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! app/core/utils/react2angular */ "./public/app/core/utils/react2angular.ts");
// Services



// Components














// angular wrappers

Object(app_core_utils_react2angular__WEBPACK_IMPORTED_MODULE_17__["react2AngularDirective"])('dashboardPermissions', _components_DashboardPermissions_DashboardPermissions__WEBPACK_IMPORTED_MODULE_16__["default"], ['dashboardId', 'folder']);


/***/ }),

/***/ "./public/app/features/dashboard/panel_editor/QueryEditorRow.tsx":
/*!***********************************************************************!*\
  !*** ./public/app/features/dashboard/panel_editor/QueryEditorRow.tsx ***!
  \***********************************************************************/
/*! exports provided: QueryEditorRow, filterPanelDataToQuery */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryEditorRow", function() { return QueryEditorRow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterPanelDataToQuery", function() { return filterPanelDataToQuery; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/plugins/datasource_srv */ "./public/app/features/plugins/datasource_srv.ts");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/features/dashboard/services/TimeSrv */ "./public/app/features/dashboard/services/TimeSrv.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libraries



// Utils & Services





var QueryEditorRow = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueryEditorRow, _super);
    function QueryEditorRow() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.element = null;
        _this.angularQueryEditor = null;
        _this.state = {
            datasource: null,
            isCollapsed: false,
            loadedDataSourceValue: undefined,
            hasTextEditMode: false,
            queryResponse: null,
        };
        _this.onToggleCollapse = function () {
            _this.setState({ isCollapsed: !_this.state.isCollapsed });
        };
        _this.onRunQuery = function () {
            _this.props.panel.refresh();
        };
        _this.onToggleEditMode = function () {
            if (_this.angularScope && _this.angularScope.toggleEditorMode) {
                _this.angularScope.toggleEditorMode();
                _this.angularQueryEditor.digest();
            }
            if (_this.state.isCollapsed) {
                _this.setState({ isCollapsed: false });
            }
        };
        _this.onRemoveQuery = function () {
            _this.props.onRemoveQuery(_this.props.query);
        };
        _this.onCopyQuery = function () {
            var copy = lodash__WEBPACK_IMPORTED_MODULE_3___default.a.cloneDeep(_this.props.query);
            _this.props.onAddQuery(copy);
        };
        _this.onDisableQuery = function () {
            _this.props.query.hide = !_this.props.query.hide;
            _this.onRunQuery();
            _this.forceUpdate();
        };
        return _this;
    }
    QueryEditorRow.prototype.componentDidMount = function () {
        this.loadDatasource();
    };
    QueryEditorRow.prototype.componentWillUnmount = function () {
        if (this.angularQueryEditor) {
            this.angularQueryEditor.destroy();
        }
    };
    QueryEditorRow.prototype.getAngularQueryComponentScope = function () {
        var _a = this.props, panel = _a.panel, query = _a.query, dashboard = _a.dashboard;
        var datasource = this.state.datasource;
        return {
            datasource: datasource,
            target: query,
            panel: panel,
            dashboard: dashboard,
            refresh: function () { return panel.refresh(); },
            render: function () { return panel.render(); },
            events: panel.events,
            range: Object(app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_6__["getTimeSrv"])().timeRange(),
        };
    };
    QueryEditorRow.prototype.loadDatasource = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var _a, query, panel, dataSourceSrv, datasource;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.props, query = _a.query, panel = _a.panel;
                        dataSourceSrv = Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_4__["getDatasourceSrv"])();
                        return [4 /*yield*/, dataSourceSrv.get(query.datasource || panel.datasource)];
                    case 1:
                        datasource = _b.sent();
                        this.setState({
                            datasource: datasource,
                            loadedDataSourceValue: this.props.dataSourceValue,
                            hasTextEditMode: lodash__WEBPACK_IMPORTED_MODULE_3___default.a.has(datasource, 'components.QueryCtrl.prototype.toggleEditorMode'),
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    QueryEditorRow.prototype.componentDidUpdate = function (prevProps) {
        var loadedDataSourceValue = this.state.loadedDataSourceValue;
        var _a = this.props, data = _a.data, query = _a.query, panel = _a.panel;
        if (data !== prevProps.data) {
            this.setState({ queryResponse: filterPanelDataToQuery(data, query.refId) });
            if (this.angularScope) {
                this.angularScope.range = Object(app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_6__["getTimeSrv"])().timeRange();
            }
            if (this.angularQueryEditor) {
                notifyAngularQueryEditorsOfData(panel, data, this.angularQueryEditor);
            }
        }
        // check if we need to load another datasource
        if (loadedDataSourceValue !== this.props.dataSourceValue) {
            if (this.angularQueryEditor) {
                this.angularQueryEditor.destroy();
                this.angularQueryEditor = null;
            }
            this.loadDatasource();
            return;
        }
        if (!this.element || this.angularQueryEditor) {
            return;
        }
        var loader = Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_5__["getAngularLoader"])();
        var template = '<plugin-component type="query-ctrl" />';
        var scopeProps = { ctrl: this.getAngularQueryComponentScope() };
        this.angularQueryEditor = loader.load(this.element, scopeProps, template);
        this.angularScope = scopeProps.ctrl;
    };
    QueryEditorRow.prototype.renderPluginEditor = function () {
        var _this = this;
        var _a = this.props, query = _a.query, data = _a.data, onChange = _a.onChange;
        var _b = this.state, datasource = _b.datasource, queryResponse = _b.queryResponse;
        if (datasource.components.QueryCtrl) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: function (element) { return (_this.element = element); } });
        }
        if (datasource.components.QueryEditor) {
            var QueryEditor = datasource.components.QueryEditor;
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(QueryEditor, { query: query, datasource: datasource, onChange: onChange, onRunQuery: this.onRunQuery, queryResponse: queryResponse, panelData: data }));
        }
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, "Data source plugin does not export any Query Editor component");
    };
    QueryEditorRow.prototype.renderCollapsedText = function () {
        var datasource = this.state.datasource;
        if (datasource.getQueryDisplayText) {
            return datasource.getQueryDisplayText(this.props.query);
        }
        if (this.angularScope && this.angularScope.getCollapsedText) {
            return this.angularScope.getCollapsedText();
        }
        return null;
    };
    QueryEditorRow.prototype.render = function () {
        var _this = this;
        var _a = this.props, query = _a.query, inMixedMode = _a.inMixedMode;
        var _b = this.state, datasource = _b.datasource, isCollapsed = _b.isCollapsed, hasTextEditMode = _b.hasTextEditMode;
        var isDisabled = query.hide;
        var bodyClasses = classnames__WEBPACK_IMPORTED_MODULE_2___default()('query-editor-row__body gf-form-query', {
            'query-editor-row__body--collapsed': isCollapsed,
        });
        var rowClasses = classnames__WEBPACK_IMPORTED_MODULE_2___default()('query-editor-row', {
            'query-editor-row--disabled': isDisabled,
            'gf-form-disabled': isDisabled,
        });
        if (!datasource) {
            return null;
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: rowClasses },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__header" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__ref-id", onClick: this.onToggleCollapse },
                    isCollapsed && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-right" }),
                    !isCollapsed && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-down" }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, query.refId),
                    inMixedMode && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("em", { className: "query-editor-row__context-info" },
                        " (",
                        datasource.name,
                        ")"),
                    isDisabled && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("em", { className: "query-editor-row__context-info" }, " Disabled")),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__collapsed-text", onClick: this.onToggleEditMode }, isCollapsed && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, this.renderCollapsedText())),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__actions" },
                    hasTextEditMode && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "query-editor-row__action", onClick: this.onToggleEditMode, title: "Toggle text edit mode" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-pencil" }))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "query-editor-row__action", onClick: function () { return _this.props.onMoveQuery(query, 1); } },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-arrow-down" })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "query-editor-row__action", onClick: function () { return _this.props.onMoveQuery(query, -1); } },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-arrow-up" })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "query-editor-row__action", onClick: this.onCopyQuery, title: "Duplicate query" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-copy" })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "query-editor-row__action", onClick: this.onDisableQuery, title: "Disable/enable query" },
                        isDisabled && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-eye-slash" }),
                        !isDisabled && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-eye" })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "query-editor-row__action", onClick: this.onRemoveQuery, title: "Remove query" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-fw fa-trash" })))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: bodyClasses },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_7__["ErrorBoundaryAlert"], null, this.renderPluginEditor()))));
    };
    return QueryEditorRow;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

// To avoid sending duplicate events for each row we have this global cached object here
// So we can check if we already emitted this legacy data event
var globalLastPanelDataCache = null;
function notifyAngularQueryEditorsOfData(panel, data, editor) {
    if (data === globalLastPanelDataCache) {
        return;
    }
    globalLastPanelDataCache = data;
    if (data.state === _grafana_data__WEBPACK_IMPORTED_MODULE_8__["LoadingState"].Done) {
        var legacy = data.series.map(function (v) { return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_8__["toLegacyResponseData"])(v); });
        panel.events.emit('data-received', legacy);
    }
    else if (data.state === _grafana_data__WEBPACK_IMPORTED_MODULE_8__["LoadingState"].Error) {
        panel.events.emit('data-error', data.error);
    }
    // Some query controllers listen to data error events and need a digest
    // for some reason this needs to be done in next tick
    setTimeout(editor.digest);
}
/**
 * Get a version of the PanelData limited to the query we are looking at
 */
function filterPanelDataToQuery(data, refId) {
    var series = data.series.filter(function (series) { return series.refId === refId; });
    // No matching series
    if (!series.length) {
        return undefined;
    }
    // Don't pass the request if all requests are the same
    var request = undefined;
    // TODO: look in sub-requets to match the info
    // Only say this is an error if the error links to the query
    var state = _grafana_data__WEBPACK_IMPORTED_MODULE_8__["LoadingState"].Done;
    var error = data.error && data.error.refId === refId ? data.error : undefined;
    if (error) {
        state = _grafana_data__WEBPACK_IMPORTED_MODULE_8__["LoadingState"].Error;
    }
    var timeRange = data.timeRange;
    return {
        state: state,
        series: series,
        request: request,
        error: error,
        timeRange: timeRange,
    };
}


/***/ }),

/***/ "./public/app/features/dashboard/panel_editor/state/actions.ts":
/*!*********************************************************************!*\
  !*** ./public/app/features/dashboard/panel_editor/state/actions.ts ***!
  \*********************************************************************/
/*! exports provided: panelEditorInitCompleted, panelEditorCleanUp, refreshPanelEditor, changePanelEditorTab */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "panelEditorInitCompleted", function() { return panelEditorInitCompleted; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "panelEditorCleanUp", function() { return panelEditorCleanUp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refreshPanelEditor", function() { return refreshPanelEditor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changePanelEditorTab", function() { return changePanelEditorTab; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _core_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../../core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var _reducers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./reducers */ "./public/app/features/dashboard/panel_editor/state/reducers.ts");
/* harmony import */ var _core_actions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../core/actions */ "./public/app/core/actions/index.ts");
var _this = undefined;




var panelEditorInitCompleted = Object(_core_redux__WEBPACK_IMPORTED_MODULE_1__["actionCreatorFactory"])('PANEL_EDITOR_INIT_COMPLETED').create();
var panelEditorCleanUp = Object(_core_redux__WEBPACK_IMPORTED_MODULE_1__["noPayloadActionCreatorFactory"])('PANEL_EDITOR_CLEAN_UP').create();
var refreshPanelEditor = function (props) {
    return function (dispatch, getState) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var activeTab, hasQueriesTab, usesGraphPlugin, alertingEnabled, tabs;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            activeTab = getState().panelEditor.activeTab || _reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Queries;
            hasQueriesTab = props.hasQueriesTab, usesGraphPlugin = props.usesGraphPlugin, alertingEnabled = props.alertingEnabled;
            tabs = [
                Object(_reducers__WEBPACK_IMPORTED_MODULE_2__["getPanelEditorTab"])(_reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Queries),
                Object(_reducers__WEBPACK_IMPORTED_MODULE_2__["getPanelEditorTab"])(_reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Visualization),
                Object(_reducers__WEBPACK_IMPORTED_MODULE_2__["getPanelEditorTab"])(_reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Advanced),
            ];
            // handle panels that do not have queries tab
            if (!hasQueriesTab) {
                // remove queries tab
                tabs.shift();
                // switch tab
                if (activeTab === _reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Queries) {
                    activeTab = _reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Visualization;
                }
            }
            if (alertingEnabled && usesGraphPlugin) {
                tabs.push(Object(_reducers__WEBPACK_IMPORTED_MODULE_2__["getPanelEditorTab"])(_reducers__WEBPACK_IMPORTED_MODULE_2__["PanelEditorTabIds"].Alert));
            }
            dispatch(panelEditorInitCompleted({ activeTab: activeTab, tabs: tabs }));
            return [2 /*return*/];
        });
    }); };
};
var changePanelEditorTab = function (activeTab) {
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            dispatch(Object(_core_actions__WEBPACK_IMPORTED_MODULE_3__["updateLocation"])({ query: { tab: activeTab.id, openVizPicker: null }, partial: true }));
            return [2 /*return*/];
        });
    }); };
};


/***/ }),

/***/ "./public/app/features/dashboard/panel_editor/state/reducers.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/panel_editor/state/reducers.ts ***!
  \**********************************************************************/
/*! exports provided: PanelEditorTabIds, panelEditorTabTexts, getPanelEditorTab, initialState, panelEditorReducer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelEditorTabIds", function() { return PanelEditorTabIds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "panelEditorTabTexts", function() { return panelEditorTabTexts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelEditorTab", function() { return getPanelEditorTab; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "panelEditorReducer", function() { return panelEditorReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _core_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../../core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./actions */ "./public/app/features/dashboard/panel_editor/state/actions.ts");
var _a;



var PanelEditorTabIds;
(function (PanelEditorTabIds) {
    PanelEditorTabIds["Queries"] = "queries";
    PanelEditorTabIds["Visualization"] = "visualization";
    PanelEditorTabIds["Advanced"] = "advanced";
    PanelEditorTabIds["Alert"] = "alert";
})(PanelEditorTabIds || (PanelEditorTabIds = {}));
var panelEditorTabTexts = (_a = {},
    _a[PanelEditorTabIds.Queries] = 'Queries',
    _a[PanelEditorTabIds.Visualization] = 'Visualization',
    _a[PanelEditorTabIds.Advanced] = 'General',
    _a[PanelEditorTabIds.Alert] = 'Alert',
    _a);
var getPanelEditorTab = function (tabId) {
    return {
        id: tabId,
        text: panelEditorTabTexts[tabId],
    };
};
var initialState = {
    activeTab: null,
    tabs: [],
};
var panelEditorReducer = Object(_core_redux__WEBPACK_IMPORTED_MODULE_1__["reducerFactory"])(initialState)
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["panelEditorInitCompleted"],
    mapper: function (state, action) {
        var _a = action.payload, activeTab = _a.activeTab, tabs = _a.tabs;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { activeTab: activeTab,
            tabs: tabs });
    },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["panelEditorCleanUp"],
    mapper: function () { return initialState; },
})
    .create();


/***/ }),

/***/ "./public/app/features/dashboard/services/ChangeTracker.ts":
/*!*****************************************************************!*\
  !*** ./public/app/features/dashboard/services/ChangeTracker.ts ***!
  \*****************************************************************/
/*! exports provided: ChangeTracker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChangeTracker", function() { return ChangeTracker; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _state_DashboardModel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../state/DashboardModel */ "./public/app/features/dashboard/state/DashboardModel.ts");



var ChangeTracker = /** @class */ (function () {
    /** @ngInject */
    function ChangeTracker(dashboard, scope, originalCopyDelay, $location, $window, $timeout, contextSrv, $rootScope) {
        var _this = this;
        this.$location = $location;
        this.$timeout = $timeout;
        this.contextSrv = contextSrv;
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.$window = $window;
        this.current = dashboard;
        this.originalPath = $location.path();
        this.scope = scope;
        // register events
        scope.onAppEvent('dashboard-saved', function () {
            _this.original = _this.current.getSaveModelClone();
            _this.originalPath = $location.path();
        });
        $window.onbeforeunload = function () {
            if (_this.ignoreChanges()) {
                return undefined;
            }
            if (_this.hasChanges()) {
                return 'There are unsaved changes to this dashboard';
            }
            return undefined;
        };
        scope.$on('$locationChangeStart', function (event, next) {
            // check if we should look for changes
            if (_this.originalPath === $location.path()) {
                return true;
            }
            if (_this.ignoreChanges()) {
                return true;
            }
            if (_this.hasChanges()) {
                event.preventDefault();
                _this.next = next;
                _this.$timeout(function () {
                    _this.open_modal();
                });
            }
            return false;
        });
        if (originalCopyDelay && !dashboard.meta.fromExplore) {
            this.$timeout(function () {
                // wait for different services to patch the dashboard (missing properties)
                _this.original = dashboard.getSaveModelClone();
            }, originalCopyDelay);
        }
        else {
            this.original = dashboard.getSaveModelClone();
        }
    }
    // for some dashboards and users
    // changes should be ignored
    ChangeTracker.prototype.ignoreChanges = function () {
        if (!this.original) {
            return true;
        }
        if (!this.contextSrv.isEditor) {
            return true;
        }
        if (!this.current || !this.current.meta) {
            return true;
        }
        var meta = this.current.meta;
        return !meta.canSave || meta.fromScript || meta.fromFile;
    };
    // remove stuff that should not count in diff
    ChangeTracker.prototype.cleanDashboardFromIgnoredChanges = function (dashData) {
        // need to new up the domain model class to get access to expand / collapse row logic
        var model = new _state_DashboardModel__WEBPACK_IMPORTED_MODULE_2__["DashboardModel"](dashData);
        // Expand all rows before making comparison. This is required because row expand / collapse
        // change order of panel array and panel positions.
        model.expandRows();
        var dash = model.getSaveModelClone();
        // ignore time and refresh
        dash.time = 0;
        dash.refresh = 0;
        dash.schemaVersion = 0;
        // ignore iteration property
        delete dash.iteration;
        dash.panels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(dash.panels, function (panel) {
            if (panel.repeatPanelId) {
                return false;
            }
            // remove scopedVars
            panel.scopedVars = null;
            // ignore panel legend sort
            if (panel.legend) {
                delete panel.legend.sort;
                delete panel.legend.sortDesc;
            }
            return true;
        });
        // ignore template variable values
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(dash.templating.list, function (value) {
            value.current = null;
            value.options = null;
            value.filters = null;
        });
        return dash;
    };
    ChangeTracker.prototype.hasChanges = function () {
        var current = this.cleanDashboardFromIgnoredChanges(this.current.getSaveModelClone());
        var original = this.cleanDashboardFromIgnoredChanges(this.original);
        var currentTimepicker = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(current.nav, { type: 'timepicker' });
        var originalTimepicker = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(original.nav, { type: 'timepicker' });
        if (currentTimepicker && originalTimepicker) {
            currentTimepicker.now = originalTimepicker.now;
        }
        var currentJson = angular__WEBPACK_IMPORTED_MODULE_0___default.a.toJson(current, true);
        var originalJson = angular__WEBPACK_IMPORTED_MODULE_0___default.a.toJson(original, true);
        return currentJson !== originalJson;
    };
    ChangeTracker.prototype.discardChanges = function () {
        this.original = null;
        this.gotoNext();
    };
    ChangeTracker.prototype.open_modal = function () {
        this.$rootScope.appEvent('show-modal', {
            templateHtml: '<unsaved-changes-modal dismiss="dismiss()"></unsaved-changes-modal>',
            modalClass: 'modal--narrow confirm-modal',
        });
    };
    ChangeTracker.prototype.saveChanges = function () {
        var _this = this;
        var self = this;
        var cancel = this.$rootScope.$on('dashboard-saved', function () {
            cancel();
            _this.$timeout(function () {
                self.gotoNext();
            });
        });
        this.$rootScope.appEvent('save-dashboard');
    };
    ChangeTracker.prototype.gotoNext = function () {
        var baseLen = this.$location.absUrl().length - this.$location.url().length;
        var nextUrl = this.next.substring(baseLen);
        this.$location.url(nextUrl);
    };
    return ChangeTracker;
}());



/***/ }),

/***/ "./public/app/features/dashboard/services/DashboardLoaderSrv.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/dashboard/services/DashboardLoaderSrv.ts ***!
  \**********************************************************************/
/*! exports provided: DashboardLoaderSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardLoaderSrv", function() { return DashboardLoaderSrv; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! moment */ "./node_modules/moment/moment.js");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/services/impression_srv */ "./public/app/core/services/impression_srv.ts");
/* tslint:disable:import-blacklist */







var DashboardLoaderSrv = /** @class */ (function () {
    /** @ngInject */
    function DashboardLoaderSrv(backendSrv, dashboardSrv, datasourceSrv, $http, $q, $timeout, contextSrv, $routeParams, $rootScope) {
        this.backendSrv = backendSrv;
        this.dashboardSrv = dashboardSrv;
        this.datasourceSrv = datasourceSrv;
        this.$http = $http;
        this.$q = $q;
        this.$timeout = $timeout;
        this.$routeParams = $routeParams;
        this.$rootScope = $rootScope;
    }
    DashboardLoaderSrv.prototype._dashboardLoadFailed = function (title, snapshot) {
        snapshot = snapshot || false;
        return {
            meta: {
                canStar: false,
                isSnapshot: snapshot,
                canDelete: false,
                canSave: false,
                canEdit: false,
                dashboardNotFound: true,
            },
            dashboard: { title: title },
        };
    };
    DashboardLoaderSrv.prototype.loadDashboard = function (type, slug, uid) {
        var _this = this;
        var promise;
        if (type === 'script') {
            promise = this._loadScriptedDashboard(slug);
        }
        else if (type === 'snapshot') {
            promise = this.backendSrv.get('/api/snapshots/' + slug).catch(function () {
                return _this._dashboardLoadFailed('Snapshot not found', true);
            });
        }
        else {
            promise = this.backendSrv
                .getDashboardByUid(uid)
                .then(function (result) {
                if (result.meta.isFolder) {
                    _this.$rootScope.appEvent('alert-error', ['Dashboard not found']);
                    throw new Error('Dashboard not found');
                }
                return result;
            })
                .catch(function () {
                return _this._dashboardLoadFailed('Not found', true);
            });
        }
        promise.then(function (result) {
            if (result.meta.dashboardNotFound !== true) {
                app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_6__["default"].addDashboardImpression(result.dashboard.id);
            }
            return result;
        });
        return promise;
    };
    DashboardLoaderSrv.prototype._loadScriptedDashboard = function (file) {
        var _this = this;
        var url = 'public/dashboards/' + file.replace(/\.(?!js)/, '/') + '?' + new Date().getTime();
        return this.$http({ url: url, method: 'GET' })
            .then(this._executeScript.bind(this))
            .then(function (result) {
            return {
                meta: {
                    fromScript: true,
                    canDelete: false,
                    canSave: false,
                    canStar: false,
                },
                dashboard: result.data,
            };
        }, function (err) {
            console.log('Script dashboard error ' + err);
            _this.$rootScope.appEvent('alert-error', [
                'Script Error',
                'Please make sure it exists and returns a valid dashboard',
            ]);
            return _this._dashboardLoadFailed('Scripted dashboard');
        });
    };
    DashboardLoaderSrv.prototype._executeScript = function (result) {
        var _this = this;
        var services = {
            dashboardSrv: this.dashboardSrv,
            datasourceSrv: this.datasourceSrv,
            $q: this.$q,
        };
        /*jshint -W054 */
        var scriptFunc = new Function('ARGS', 'kbn', 'dateMath', '_', 'moment', 'window', 'document', '$', 'jQuery', 'services', result.data);
        var scriptResult = scriptFunc(this.$routeParams, app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_4__["default"], _grafana_data__WEBPACK_IMPORTED_MODULE_5__["dateMath"], lodash__WEBPACK_IMPORTED_MODULE_2___default.a, moment__WEBPACK_IMPORTED_MODULE_1___default.a, window, document, jquery__WEBPACK_IMPORTED_MODULE_3___default.a, jquery__WEBPACK_IMPORTED_MODULE_3___default.a, services);
        // Handle async dashboard scripts
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isFunction(scriptResult)) {
            var deferred_1 = this.$q.defer();
            scriptResult(function (dashboard) {
                _this.$timeout(function () {
                    deferred_1.resolve({ data: dashboard });
                });
            });
            return deferred_1.promise;
        }
        return { data: scriptResult };
    };
    return DashboardLoaderSrv;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.services').service('dashboardLoaderSrv', DashboardLoaderSrv);


/***/ }),

/***/ "./public/app/features/dashboard/services/DashboardSrv.ts":
/*!****************************************************************!*\
  !*** ./public/app/features/dashboard/services/DashboardSrv.ts ***!
  \****************************************************************/
/*! exports provided: DashboardSrv, setDashboardSrv, getDashboardSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardSrv", function() { return DashboardSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDashboardSrv", function() { return setDashboardSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDashboardSrv", function() { return getDashboardSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");
/* harmony import */ var _state_DashboardModel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../state/DashboardModel */ "./public/app/features/dashboard/state/DashboardModel.ts");
/* harmony import */ var _utils_panel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/panel */ "./public/app/features/dashboard/utils/panel.ts");






var DashboardSrv = /** @class */ (function () {
    /** @ngInject */
    function DashboardSrv(backendSrv, $rootScope, $location) {
        var _this = this;
        this.backendSrv = backendSrv;
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.onRemovePanel = function (panelId) {
            var dashboard = _this.getCurrent();
            Object(_utils_panel__WEBPACK_IMPORTED_MODULE_5__["removePanel"])(dashboard, dashboard.getPanelById(panelId), true);
        };
        this.onPanelChangeView = function (_a) {
            var e_1, _b;
            var _c = _a.fullscreen, fullscreen = _c === void 0 ? false : _c, _d = _a.edit, edit = _d === void 0 ? false : _d, panelId = _a.panelId;
            var urlParams = _this.$location.search();
            // handle toggle logic
            // I hate using these truthy converters (!!) but in this case
            // I think it's appropriate. edit can be null/false/undefined and
            // here i want all of those to compare the same
            if (fullscreen === urlParams.fullscreen && edit === !!urlParams.edit) {
                var paramsToRemove = ['fullscreen', 'edit', 'panelId', 'tab'];
                try {
                    for (var paramsToRemove_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](paramsToRemove), paramsToRemove_1_1 = paramsToRemove_1.next(); !paramsToRemove_1_1.done; paramsToRemove_1_1 = paramsToRemove_1.next()) {
                        var key = paramsToRemove_1_1.value;
                        delete urlParams[key];
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (paramsToRemove_1_1 && !paramsToRemove_1_1.done && (_b = paramsToRemove_1.return)) _b.call(paramsToRemove_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                _this.$location.search(urlParams);
                return;
            }
            var newUrlParams = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, urlParams, { fullscreen: fullscreen || undefined, edit: edit || undefined, tab: edit ? urlParams.tab : undefined, panelId: panelId });
            Object.keys(newUrlParams).forEach(function (key) {
                if (newUrlParams[key] === undefined) {
                    delete newUrlParams[key];
                }
            });
            _this.$location.search(newUrlParams);
        };
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["appEvents"].on('save-dashboard', this.saveDashboard.bind(this), $rootScope);
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["appEvents"].on('panel-change-view', this.onPanelChangeView);
        app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["appEvents"].on('remove-panel', this.onRemovePanel);
        // Export to react
        setDashboardSrv(this);
    }
    DashboardSrv.prototype.create = function (dashboard, meta) {
        return new _state_DashboardModel__WEBPACK_IMPORTED_MODULE_4__["DashboardModel"](dashboard, meta);
    };
    DashboardSrv.prototype.setCurrent = function (dashboard) {
        this.dashboard = dashboard;
    };
    DashboardSrv.prototype.getCurrent = function () {
        return this.dashboard;
    };
    DashboardSrv.prototype.handleSaveDashboardError = function (clone, options, err) {
        var _this = this;
        options.overwrite = true;
        if (err.data && err.data.status === 'version-mismatch') {
            err.isHandled = true;
            this.$rootScope.appEvent('confirm-modal', {
                title: 'Conflict',
                text: 'Someone else has updated this dashboard.',
                text2: 'Would you still like to save this dashboard?',
                yesText: 'Save & Overwrite',
                icon: 'fa-warning',
                onConfirm: function () {
                    _this.save(clone, options);
                },
            });
        }
        if (err.data && err.data.status === 'name-exists') {
            err.isHandled = true;
            this.$rootScope.appEvent('confirm-modal', {
                title: 'Conflict',
                text: 'A dashboard with the same name in selected folder already exists.',
                text2: 'Would you still like to save this dashboard?',
                yesText: 'Save & Overwrite',
                icon: 'fa-warning',
                onConfirm: function () {
                    _this.save(clone, options);
                },
            });
        }
        if (err.data && err.data.status === 'plugin-dashboard') {
            err.isHandled = true;
            this.$rootScope.appEvent('confirm-modal', {
                title: 'Plugin Dashboard',
                text: err.data.message,
                text2: 'Your changes will be lost when you update the plugin. Use Save As to create custom version.',
                yesText: 'Overwrite',
                icon: 'fa-warning',
                altActionText: 'Save As',
                onAltAction: function () {
                    _this.showSaveAsModal();
                },
                onConfirm: function () {
                    _this.save(clone, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { overwrite: true }));
                },
            });
        }
    };
    DashboardSrv.prototype.postSave = function (data) {
        this.dashboard.version = data.version;
        // important that these happen before location redirect below
        this.$rootScope.appEvent('dashboard-saved', this.dashboard);
        this.$rootScope.appEvent('alert-success', ['Dashboard saved']);
        var newUrl = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__["default"].stripBaseFromUrl(data.url);
        var currentPath = this.$location.path();
        if (newUrl !== currentPath) {
            this.$location.url(newUrl).replace();
        }
        return this.dashboard;
    };
    DashboardSrv.prototype.save = function (clone, options) {
        var _this = this;
        options.folderId = options.folderId >= 0 ? options.folderId : this.dashboard.meta.folderId || clone.folderId;
        return this.backendSrv
            .saveDashboard(clone, options)
            .then(function (data) { return _this.postSave(data); })
            .catch(this.handleSaveDashboardError.bind(this, clone, { folderId: options.folderId }));
    };
    DashboardSrv.prototype.saveDashboard = function (clone, _a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.makeEditable, makeEditable = _c === void 0 ? false : _c, folderId = _b.folderId, _d = _b.overwrite, overwrite = _d === void 0 ? false : _d, message = _b.message;
        if (clone) {
            this.setCurrent(this.create(clone, this.dashboard.meta));
        }
        if (this.dashboard.meta.provisioned) {
            return this.showDashboardProvisionedModal();
        }
        if (!(this.dashboard.meta.canSave || makeEditable)) {
            return Promise.resolve();
        }
        if (this.dashboard.title === 'New dashboard') {
            return this.showSaveAsModal();
        }
        if (this.dashboard.version > 0) {
            return this.showSaveModal();
        }
        return this.save(this.dashboard.getSaveModelClone(), { folderId: folderId, overwrite: overwrite, message: message });
    };
    DashboardSrv.prototype.saveJSONDashboard = function (json) {
        return this.save(JSON.parse(json), {});
    };
    DashboardSrv.prototype.showDashboardProvisionedModal = function () {
        this.$rootScope.appEvent('show-modal', {
            templateHtml: '<save-provisioned-dashboard-modal dismiss="dismiss()"></save-provisioned-dashboard-modal>',
        });
    };
    DashboardSrv.prototype.showSaveAsModal = function () {
        this.$rootScope.appEvent('show-modal', {
            templateHtml: '<save-dashboard-as-modal dismiss="dismiss()"></save-dashboard-as-modal>',
            modalClass: 'modal--narrow',
        });
    };
    DashboardSrv.prototype.showSaveModal = function () {
        this.$rootScope.appEvent('show-modal', {
            templateHtml: '<save-dashboard-modal dismiss="dismiss()"></save-dashboard-modal>',
            modalClass: 'modal--narrow',
        });
    };
    DashboardSrv.prototype.starDashboard = function (dashboardId, isStarred) {
        var _this = this;
        var promise;
        if (isStarred) {
            promise = this.backendSrv.delete('/api/user/stars/dashboard/' + dashboardId).then(function () {
                return false;
            });
        }
        else {
            promise = this.backendSrv.post('/api/user/stars/dashboard/' + dashboardId).then(function () {
                return true;
            });
        }
        return promise.then(function (res) {
            if (_this.dashboard && _this.dashboard.id === dashboardId) {
                _this.dashboard.meta.isStarred = res;
            }
            return res;
        });
    };
    return DashboardSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('dashboardSrv', DashboardSrv);
//
// Code below is to export the service to react components
//
var singletonInstance;
function setDashboardSrv(instance) {
    singletonInstance = instance;
}
function getDashboardSrv() {
    return singletonInstance;
}


/***/ }),

/***/ "./public/app/features/dashboard/services/TimeSrv.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/dashboard/services/TimeSrv.ts ***!
  \***********************************************************/
/*! exports provided: TimeSrv, setTimeSrv, getTimeSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeSrv", function() { return TimeSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setTimeSrv", function() { return setTimeSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeSrv", function() { return getTimeSrv; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_utils_timePicker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/timePicker */ "./public/app/core/utils/timePicker.ts");
// Libraries

// Utils


// Types


var TimeSrv = /** @class */ (function () {
    /** @ngInject */
    function TimeSrv($rootScope, $timeout, $location, timer, contextSrv) {
        var _this = this;
        this.$timeout = $timeout;
        this.$location = $location;
        this.timer = timer;
        this.contextSrv = contextSrv;
        // default time
        this.time = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["DefaultTimeRange"].raw;
        $rootScope.$on('zoom-out', this.zoomOut.bind(this));
        $rootScope.$on('shift-time', this.shiftTime.bind(this));
        $rootScope.$on('$routeUpdate', this.routeUpdated.bind(this));
        document.addEventListener('visibilitychange', function () {
            if (_this.autoRefreshBlocked && document.visibilityState === 'visible') {
                _this.autoRefreshBlocked = false;
                _this.refreshDashboard();
            }
        });
    }
    TimeSrv.prototype.init = function (dashboard) {
        this.timer.cancelAll();
        this.dashboard = dashboard;
        this.time = dashboard.time;
        this.refresh = dashboard.refresh;
        this.initTimeFromUrl();
        this.parseTime();
        // remember time at load so we can go back to it
        this.timeAtLoad = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.cloneDeep(this.time);
        if (this.refresh) {
            this.setAutoRefresh(this.refresh);
        }
    };
    TimeSrv.prototype.parseTime = function () {
        // when absolute time is saved in json it is turned to a string
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(this.time.from) && this.time.from.indexOf('Z') >= 0) {
            this.time.from = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(this.time.from).utc();
        }
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(this.time.to) && this.time.to.indexOf('Z') >= 0) {
            this.time.to = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(this.time.to).utc();
        }
    };
    TimeSrv.prototype.parseUrlParam = function (value) {
        if (value.indexOf('now') !== -1) {
            return value;
        }
        if (value.length === 8) {
            return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(value, 'YYYYMMDD');
        }
        if (value.length === 15) {
            return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(value, 'YYYYMMDDTHHmmss');
        }
        if (!isNaN(value)) {
            var epoch = parseInt(value, 10);
            return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(epoch);
        }
        return null;
    };
    TimeSrv.prototype.getTimeWindow = function (time, timeWindow) {
        var valueTime = parseInt(time, 10);
        var timeWindowMs;
        if (timeWindow.match(/^\d+$/) && parseInt(timeWindow, 10)) {
            // when time window specified in ms
            timeWindowMs = parseInt(timeWindow, 10);
        }
        else {
            timeWindowMs = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__["default"].interval_to_ms(timeWindow);
        }
        return {
            from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(valueTime - timeWindowMs / 2),
            to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(valueTime + timeWindowMs / 2),
        };
    };
    TimeSrv.prototype.initTimeFromUrl = function () {
        var params = this.$location.search();
        if (params.time && params['time.window']) {
            this.time = this.getTimeWindow(params.time, params['time.window']);
        }
        if (params.from) {
            this.time.from = this.parseUrlParam(params.from) || this.time.from;
        }
        if (params.to) {
            this.time.to = this.parseUrlParam(params.to) || this.time.to;
        }
        // if absolute ignore refresh option saved to dashboard
        if (params.to && params.to.indexOf('now') === -1) {
            this.refresh = false;
            this.dashboard.refresh = false;
        }
        // but if refresh explicitly set then use that
        if (params.refresh) {
            this.refresh = params.refresh || this.refresh;
        }
    };
    TimeSrv.prototype.routeUpdated = function () {
        var params = this.$location.search();
        if (params.left) {
            return; // explore handles this;
        }
        var urlRange = this.timeRangeForUrl();
        // check if url has time range
        if (params.from && params.to) {
            // is it different from what our current time range?
            if (params.from !== urlRange.from || params.to !== urlRange.to) {
                // issue update
                this.initTimeFromUrl();
                this.setTime(this.time, true);
            }
        }
        else if (this.timeHasChangedSinceLoad()) {
            this.setTime(this.timeAtLoad, true);
        }
    };
    TimeSrv.prototype.timeHasChangedSinceLoad = function () {
        return this.timeAtLoad && (this.timeAtLoad.from !== this.time.from || this.timeAtLoad.to !== this.time.to);
    };
    TimeSrv.prototype.setAutoRefresh = function (interval) {
        var _this = this;
        this.dashboard.refresh = interval;
        this.cancelNextRefresh();
        if (interval) {
            var intervalMs_1 = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__["default"].interval_to_ms(interval);
            this.refreshTimer = this.timer.register(this.$timeout(function () {
                _this.startNextRefreshTimer(intervalMs_1);
                _this.refreshDashboard();
            }, intervalMs_1));
        }
        // update url inside timeout to so that a digest happens after (called from react)
        this.$timeout(function () {
            var params = _this.$location.search();
            if (interval) {
                params.refresh = interval;
                _this.$location.search(params);
            }
            else if (params.refresh) {
                delete params.refresh;
                _this.$location.search(params);
            }
        });
    };
    TimeSrv.prototype.refreshDashboard = function () {
        this.dashboard.timeRangeUpdated(this.timeRange());
    };
    TimeSrv.prototype.startNextRefreshTimer = function (afterMs) {
        var _this = this;
        this.cancelNextRefresh();
        this.refreshTimer = this.timer.register(this.$timeout(function () {
            _this.startNextRefreshTimer(afterMs);
            if (_this.contextSrv.isGrafanaVisible()) {
                _this.refreshDashboard();
            }
            else {
                _this.autoRefreshBlocked = true;
            }
        }, afterMs));
    };
    TimeSrv.prototype.cancelNextRefresh = function () {
        this.timer.cancel(this.refreshTimer);
    };
    TimeSrv.prototype.setTime = function (time, fromRouteUpdate) {
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.extend(this.time, time);
        // disable refresh if zoom in or zoom out
        if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(time.to)) {
            this.oldRefresh = this.dashboard.refresh || this.oldRefresh;
            this.setAutoRefresh(false);
        }
        else if (this.oldRefresh && this.oldRefresh !== this.dashboard.refresh) {
            this.setAutoRefresh(this.oldRefresh);
            this.oldRefresh = null;
        }
        // update url
        if (fromRouteUpdate !== true) {
            var urlRange = this.timeRangeForUrl();
            var urlParams = this.$location.search();
            urlParams.from = urlRange.from;
            urlParams.to = urlRange.to;
            this.$location.search(urlParams);
        }
        this.$timeout(this.refreshDashboard.bind(this), 0);
    };
    TimeSrv.prototype.timeRangeForUrl = function () {
        var range = this.timeRange().raw;
        if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(range.from)) {
            range.from = range.from.valueOf().toString();
        }
        if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(range.to)) {
            range.to = range.to.valueOf().toString();
        }
        return range;
    };
    TimeSrv.prototype.timeRange = function () {
        // make copies if they are moment  (do not want to return out internal moment, because they are mutable!)
        var raw = {
            from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(this.time.from) ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(this.time.from) : this.time.from,
            to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["isDateTime"])(this.time.to) ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateTime"])(this.time.to) : this.time.to,
        };
        var timezone = this.dashboard ? this.dashboard.getTimezone() : undefined;
        return {
            from: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(raw.from, false, timezone),
            to: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(raw.to, true, timezone),
            raw: raw,
        };
    };
    TimeSrv.prototype.zoomOut = function (e, factor) {
        var range = this.timeRange();
        var _a = Object(app_core_utils_timePicker__WEBPACK_IMPORTED_MODULE_4__["getZoomedTimeRange"])(range, factor), from = _a.from, to = _a.to;
        this.setTime({ from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(from), to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(to) });
    };
    TimeSrv.prototype.shiftTime = function (e, direction) {
        var range = this.timeRange();
        var _a = Object(app_core_utils_timePicker__WEBPACK_IMPORTED_MODULE_4__["getShiftedTimeRange"])(direction, range), from = _a.from, to = _a.to;
        this.setTime({
            from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(from),
            to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toUtc"])(to),
        });
    };
    return TimeSrv;
}());

var singleton;
function setTimeSrv(srv) {
    singleton = srv;
}
function getTimeSrv() {
    return singleton;
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].service('timeSrv', TimeSrv);


/***/ }),

/***/ "./public/app/features/dashboard/services/UnsavedChangesSrv.ts":
/*!*********************************************************************!*\
  !*** ./public/app/features/dashboard/services/UnsavedChangesSrv.ts ***!
  \*********************************************************************/
/*! exports provided: unsavedChangesSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unsavedChangesSrv", function() { return unsavedChangesSrv; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _ChangeTracker__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ChangeTracker */ "./public/app/features/dashboard/services/ChangeTracker.ts");


/** @ngInject */
function unsavedChangesSrv($rootScope, $q, $location, $timeout, contextSrv, dashboardSrv, $window) {
    this.init = function (dashboard, scope) {
        this.tracker = new _ChangeTracker__WEBPACK_IMPORTED_MODULE_1__["ChangeTracker"](dashboard, scope, 1000, $location, $window, $timeout, contextSrv, $rootScope);
        return this.tracker;
    };
}
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.services').service('unsavedChangesSrv', unsavedChangesSrv);


/***/ }),

/***/ "./public/app/features/dashboard/state/DashboardMigrator.ts":
/*!******************************************************************!*\
  !*** ./public/app/features/dashboard/state/DashboardMigrator.ts ***!
  \******************************************************************/
/*! exports provided: DashboardMigrator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardMigrator", function() { return DashboardMigrator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_factors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/factors */ "./public/app/core/utils/factors.ts");
/* harmony import */ var app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/url */ "./public/app/core/utils/url.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var _PanelModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./PanelModel */ "./public/app/features/dashboard/state/PanelModel.ts");
/* harmony import */ var app_core_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/constants */ "./public/app/core/constants.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Utils



// Types

// Constants


var DashboardMigrator = /** @class */ (function () {
    function DashboardMigrator(dashboardModel) {
        this.dashboard = dashboardModel;
    }
    DashboardMigrator.prototype.updateSchema = function (old) {
        var i, j, k, n;
        var oldVersion = this.dashboard.schemaVersion;
        var panelUpgrades = [];
        this.dashboard.schemaVersion = 20;
        if (oldVersion === this.dashboard.schemaVersion) {
            return;
        }
        // version 2 schema changes
        if (oldVersion < 2) {
            if (old.services) {
                if (old.services.filter) {
                    this.dashboard.time = old.services.filter.time;
                    this.dashboard.templating.list = old.services.filter.list || [];
                }
            }
            panelUpgrades.push(function (panel) {
                // rename panel type
                if (panel.type === 'graphite') {
                    panel.type = 'graph';
                }
                if (panel.type !== 'graph') {
                    return;
                }
                if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isBoolean(panel.legend)) {
                    panel.legend = { show: panel.legend };
                }
                if (panel.grid) {
                    if (panel.grid.min) {
                        panel.grid.leftMin = panel.grid.min;
                        delete panel.grid.min;
                    }
                    if (panel.grid.max) {
                        panel.grid.leftMax = panel.grid.max;
                        delete panel.grid.max;
                    }
                }
                if (panel.y_format) {
                    if (!panel.y_formats) {
                        panel.y_formats = [];
                    }
                    panel.y_formats[0] = panel.y_format;
                    delete panel.y_format;
                }
                if (panel.y2_format) {
                    if (!panel.y_formats) {
                        panel.y_formats = [];
                    }
                    panel.y_formats[1] = panel.y2_format;
                    delete panel.y2_format;
                }
            });
        }
        // schema version 3 changes
        if (oldVersion < 3) {
            // ensure panel ids
            var maxId_1 = this.dashboard.getNextPanelId();
            panelUpgrades.push(function (panel) {
                if (!panel.id) {
                    panel.id = maxId_1;
                    maxId_1 += 1;
                }
            });
        }
        // schema version 4 changes
        if (oldVersion < 4) {
            // move aliasYAxis changes
            panelUpgrades.push(function (panel) {
                if (panel.type !== 'graph') {
                    return;
                }
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(panel.aliasYAxis, function (value, key) {
                    panel.seriesOverrides = [{ alias: key, yaxis: value }];
                });
                delete panel.aliasYAxis;
            });
        }
        if (oldVersion < 6) {
            // move pulldowns to new schema
            var annotations = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(old.pulldowns, { type: 'annotations' });
            if (annotations) {
                this.dashboard.annotations = {
                    list: annotations.annotations || [],
                };
            }
            // update template variables
            for (i = 0; i < this.dashboard.templating.list.length; i++) {
                var variable = this.dashboard.templating.list[i];
                if (variable.datasource === void 0) {
                    variable.datasource = null;
                }
                if (variable.type === 'filter') {
                    variable.type = 'query';
                }
                if (variable.type === void 0) {
                    variable.type = 'query';
                }
                if (variable.allFormat === void 0) {
                    variable.allFormat = 'glob';
                }
            }
        }
        if (oldVersion < 7) {
            if (old.nav && old.nav.length) {
                this.dashboard.timepicker = old.nav[0];
            }
            // ensure query refIds
            panelUpgrades.push(function (panel) {
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(panel.targets, function (target) {
                    if (!target.refId) {
                        target.refId = panel.getNextQueryLetter && panel.getNextQueryLetter();
                    }
                });
            });
        }
        if (oldVersion < 8) {
            panelUpgrades.push(function (panel) {
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(panel.targets, function (target) {
                    // update old influxdb query schema
                    if (target.fields && target.tags && target.groupBy) {
                        if (target.rawQuery) {
                            delete target.fields;
                            delete target.fill;
                        }
                        else {
                            target.select = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(target.fields, function (field) {
                                var parts = [];
                                parts.push({ type: 'field', params: [field.name] });
                                parts.push({ type: field.func, params: [] });
                                if (field.mathExpr) {
                                    parts.push({ type: 'math', params: [field.mathExpr] });
                                }
                                if (field.asExpr) {
                                    parts.push({ type: 'alias', params: [field.asExpr] });
                                }
                                return parts;
                            });
                            delete target.fields;
                            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(target.groupBy, function (part) {
                                if (part.type === 'time' && part.interval) {
                                    part.params = [part.interval];
                                    delete part.interval;
                                }
                                if (part.type === 'tag' && part.key) {
                                    part.params = [part.key];
                                    delete part.key;
                                }
                            });
                            if (target.fill) {
                                target.groupBy.push({ type: 'fill', params: [target.fill] });
                                delete target.fill;
                            }
                        }
                    }
                });
            });
        }
        // schema version 9 changes
        if (oldVersion < 9) {
            // move aliasYAxis changes
            panelUpgrades.push(function (panel) {
                if (panel.type !== 'singlestat' && panel.thresholds !== '') {
                    return;
                }
                if (panel.thresholds) {
                    var k_1 = panel.thresholds.split(',');
                    if (k_1.length >= 3) {
                        k_1.shift();
                        panel.thresholds = k_1.join(',');
                    }
                }
            });
        }
        // schema version 10 changes
        if (oldVersion < 10) {
            // move aliasYAxis changes
            panelUpgrades.push(function (panel) {
                if (panel.type !== 'table') {
                    return;
                }
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(panel.styles, function (style) {
                    if (style.thresholds && style.thresholds.length >= 3) {
                        var k_2 = style.thresholds;
                        k_2.shift();
                        style.thresholds = k_2;
                    }
                });
            });
        }
        if (oldVersion < 12) {
            // update template variables
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(this.dashboard.templating.list, function (templateVariable) {
                if (templateVariable.refresh) {
                    templateVariable.refresh = 1;
                }
                if (!templateVariable.refresh) {
                    templateVariable.refresh = 0;
                }
                if (templateVariable.hideVariable) {
                    templateVariable.hide = 2;
                }
                else if (templateVariable.hideLabel) {
                    templateVariable.hide = 1;
                }
            });
        }
        if (oldVersion < 12) {
            // update graph yaxes changes
            panelUpgrades.push(function (panel) {
                if (panel.type !== 'graph') {
                    return;
                }
                if (!panel.grid) {
                    return;
                }
                if (!panel.yaxes) {
                    panel.yaxes = [
                        {
                            show: panel['y-axis'],
                            min: panel.grid.leftMin,
                            max: panel.grid.leftMax,
                            logBase: panel.grid.leftLogBase,
                            format: panel.y_formats[0],
                            label: panel.leftYAxisLabel,
                        },
                        {
                            show: panel['y-axis'],
                            min: panel.grid.rightMin,
                            max: panel.grid.rightMax,
                            logBase: panel.grid.rightLogBase,
                            format: panel.y_formats[1],
                            label: panel.rightYAxisLabel,
                        },
                    ];
                    panel.xaxis = {
                        show: panel['x-axis'],
                    };
                    delete panel.grid.leftMin;
                    delete panel.grid.leftMax;
                    delete panel.grid.leftLogBase;
                    delete panel.grid.rightMin;
                    delete panel.grid.rightMax;
                    delete panel.grid.rightLogBase;
                    delete panel.y_formats;
                    delete panel.leftYAxisLabel;
                    delete panel.rightYAxisLabel;
                    delete panel['y-axis'];
                    delete panel['x-axis'];
                }
            });
        }
        if (oldVersion < 13) {
            // update graph yaxes changes
            panelUpgrades.push(function (panel) {
                if (panel.type !== 'graph') {
                    return;
                }
                if (!panel.grid) {
                    return;
                }
                panel.thresholds = [];
                var t1 = {}, t2 = {};
                if (panel.grid.threshold1 !== null) {
                    t1.value = panel.grid.threshold1;
                    if (panel.grid.thresholdLine) {
                        t1.line = true;
                        t1.lineColor = panel.grid.threshold1Color;
                        t1.colorMode = 'custom';
                    }
                    else {
                        t1.fill = true;
                        t1.fillColor = panel.grid.threshold1Color;
                        t1.colorMode = 'custom';
                    }
                }
                if (panel.grid.threshold2 !== null) {
                    t2.value = panel.grid.threshold2;
                    if (panel.grid.thresholdLine) {
                        t2.line = true;
                        t2.lineColor = panel.grid.threshold2Color;
                        t2.colorMode = 'custom';
                    }
                    else {
                        t2.fill = true;
                        t2.fillColor = panel.grid.threshold2Color;
                        t2.colorMode = 'custom';
                    }
                }
                if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(t1.value)) {
                    if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(t2.value)) {
                        if (t1.value > t2.value) {
                            t1.op = t2.op = 'lt';
                            panel.thresholds.push(t1);
                            panel.thresholds.push(t2);
                        }
                        else {
                            t1.op = t2.op = 'gt';
                            panel.thresholds.push(t1);
                            panel.thresholds.push(t2);
                        }
                    }
                    else {
                        t1.op = 'gt';
                        panel.thresholds.push(t1);
                    }
                }
                delete panel.grid.threshold1;
                delete panel.grid.threshold1Color;
                delete panel.grid.threshold2;
                delete panel.grid.threshold2Color;
                delete panel.grid.thresholdLine;
            });
        }
        if (oldVersion < 14) {
            this.dashboard.graphTooltip = old.sharedCrosshair ? 1 : 0;
        }
        if (oldVersion < 16) {
            this.upgradeToGridLayout(old);
        }
        if (oldVersion < 17) {
            panelUpgrades.push(function (panel) {
                if (panel.minSpan) {
                    var max_1 = app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"] / panel.minSpan;
                    var factors = Object(app_core_utils_factors__WEBPACK_IMPORTED_MODULE_2__["default"])(app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"]);
                    // find the best match compared to factors
                    // (ie. [1,2,3,4,6,12,24] for 24 columns)
                    panel.maxPerRow =
                        factors[lodash__WEBPACK_IMPORTED_MODULE_1___default.a.findIndex(factors, function (o) {
                            return o > max_1;
                        }) - 1];
                }
                delete panel.minSpan;
            });
        }
        if (oldVersion < 18) {
            // migrate change to gauge options
            panelUpgrades.push(function (panel) {
                if (panel['options-gauge']) {
                    panel.options = panel['options-gauge'];
                    panel.options.valueOptions = {
                        unit: panel.options.unit,
                        stat: panel.options.stat,
                        decimals: panel.options.decimals,
                        prefix: panel.options.prefix,
                        suffix: panel.options.suffix,
                    };
                    // correct order
                    if (panel.options.thresholds) {
                        panel.options.thresholds.reverse();
                    }
                    // this options prop was due to a bug
                    delete panel.options.options;
                    delete panel.options.unit;
                    delete panel.options.stat;
                    delete panel.options.decimals;
                    delete panel.options.prefix;
                    delete panel.options.suffix;
                    delete panel['options-gauge'];
                }
            });
        }
        if (oldVersion < 19) {
            // migrate change to gauge options
            panelUpgrades.push(function (panel) {
                if (panel.links && lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(panel.links)) {
                    panel.links = panel.links.map(upgradePanelLink);
                }
            });
        }
        if (oldVersion < 20) {
            var updateLinks_1 = function (link) {
                return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, link, { url: updateVariablesSyntax(link.url) });
            };
            panelUpgrades.push(function (panel) {
                // For graph panel
                if (panel.options && panel.options.dataLinks && lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(panel.options.dataLinks)) {
                    panel.options.dataLinks = panel.options.dataLinks.map(updateLinks_1);
                }
                // For panel with fieldOptions
                if (panel.options && panel.options.fieldOptions && panel.options.fieldOptions.defaults) {
                    if (panel.options.fieldOptions.defaults.links && lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(panel.options.fieldOptions.defaults.links)) {
                        panel.options.fieldOptions.defaults.links = panel.options.fieldOptions.defaults.links.map(updateLinks_1);
                    }
                    if (panel.options.fieldOptions.defaults.title) {
                        panel.options.fieldOptions.defaults.title = updateVariablesSyntax(panel.options.fieldOptions.defaults.title);
                    }
                }
            });
        }
        if (panelUpgrades.length === 0) {
            return;
        }
        for (j = 0; j < this.dashboard.panels.length; j++) {
            for (k = 0; k < panelUpgrades.length; k++) {
                panelUpgrades[k].call(this, this.dashboard.panels[j]);
                if (this.dashboard.panels[j].panels) {
                    for (n = 0; n < this.dashboard.panels[j].panels.length; n++) {
                        panelUpgrades[k].call(this, this.dashboard.panels[j].panels[n]);
                    }
                }
            }
        }
    };
    DashboardMigrator.prototype.upgradeToGridLayout = function (old) {
        var e_1, _a, e_2, _b;
        var yPos = 0;
        var widthFactor = app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"] / 12;
        var maxPanelId = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.max(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.flattenDeep(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(old.rows, function (row) {
            return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(row.panels, 'id');
        })));
        var nextRowId = maxPanelId + 1;
        if (!old.rows) {
            return;
        }
        // Add special "row" panels if even one row is collapsed, repeated or has visible title
        var showRows = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.some(old.rows, function (row) { return row.collapse || row.showTitle || row.repeat; });
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](old.rows), _d = _c.next(); !_d.done; _d = _c.next()) {
                var row = _d.value;
                if (row.repeatIteration) {
                    continue;
                }
                var height = row.height || app_core_constants__WEBPACK_IMPORTED_MODULE_6__["DEFAULT_ROW_HEIGHT"];
                var rowGridHeight = getGridHeight(height);
                var rowPanel = {};
                var rowPanelModel = void 0;
                if (showRows) {
                    // add special row panel
                    rowPanel.id = nextRowId;
                    rowPanel.type = 'row';
                    rowPanel.title = row.title;
                    rowPanel.collapsed = row.collapse;
                    rowPanel.repeat = row.repeat;
                    rowPanel.panels = [];
                    rowPanel.gridPos = {
                        x: 0,
                        y: yPos,
                        w: app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"],
                        h: rowGridHeight,
                    };
                    rowPanelModel = new _PanelModel__WEBPACK_IMPORTED_MODULE_5__["PanelModel"](rowPanel);
                    nextRowId++;
                    yPos++;
                }
                var rowArea = new RowArea(rowGridHeight, app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"], yPos);
                try {
                    for (var _e = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](row.panels)), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var panel = _f.value;
                        panel.span = panel.span || app_core_constants__WEBPACK_IMPORTED_MODULE_6__["DEFAULT_PANEL_SPAN"];
                        if (panel.minSpan) {
                            panel.minSpan = Math.min(app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"], (app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"] / 12) * panel.minSpan);
                        }
                        var panelWidth = Math.floor(panel.span) * widthFactor;
                        var panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight;
                        var panelPos = rowArea.getPanelPosition(panelHeight, panelWidth);
                        yPos = rowArea.yPos;
                        panel.gridPos = {
                            x: panelPos.x,
                            y: yPos + panelPos.y,
                            w: panelWidth,
                            h: panelHeight,
                        };
                        rowArea.addPanel(panel.gridPos);
                        delete panel.span;
                        if (rowPanelModel && rowPanel.collapsed) {
                            rowPanelModel.panels.push(panel);
                        }
                        else {
                            this.dashboard.panels.push(new _PanelModel__WEBPACK_IMPORTED_MODULE_5__["PanelModel"](panel));
                        }
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
                if (rowPanelModel) {
                    this.dashboard.panels.push(rowPanelModel);
                }
                if (!(rowPanelModel && rowPanel.collapsed)) {
                    yPos += rowGridHeight;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    return DashboardMigrator;
}());

function getGridHeight(height) {
    if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isString(height)) {
        height = parseInt(height.replace('px', ''), 10);
    }
    if (height < app_core_constants__WEBPACK_IMPORTED_MODULE_6__["MIN_PANEL_HEIGHT"]) {
        height = app_core_constants__WEBPACK_IMPORTED_MODULE_6__["MIN_PANEL_HEIGHT"];
    }
    var gridHeight = Math.ceil(height / (app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_CELL_HEIGHT"] + app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_CELL_VMARGIN"]));
    return gridHeight;
}
/**
 * RowArea represents dashboard row filled by panels
 * area is an array of numbers represented filled column's cells like
 *  -----------------------
 * |******** ****
 * |******** ****
 * |********
 *  -----------------------
 *  33333333 2222 00000 ...
 */
var RowArea = /** @class */ (function () {
    function RowArea(height, width, rowYPos) {
        if (width === void 0) { width = app_core_constants__WEBPACK_IMPORTED_MODULE_6__["GRID_COLUMN_COUNT"]; }
        if (rowYPos === void 0) { rowYPos = 0; }
        this.area = new Array(width).fill(0);
        this.yPos = rowYPos;
        this.height = height;
    }
    RowArea.prototype.reset = function () {
        this.area.fill(0);
    };
    /**
     * Update area after adding the panel.
     */
    RowArea.prototype.addPanel = function (gridPos) {
        for (var i = gridPos.x; i < gridPos.x + gridPos.w; i++) {
            if (!this.area[i] || gridPos.y + gridPos.h - this.yPos > this.area[i]) {
                this.area[i] = gridPos.y + gridPos.h - this.yPos;
            }
        }
        return this.area;
    };
    /**
     * Calculate position for the new panel in the row.
     */
    RowArea.prototype.getPanelPosition = function (panelHeight, panelWidth, callOnce) {
        if (callOnce === void 0) { callOnce = false; }
        var startPlace, endPlace;
        var place;
        for (var i = this.area.length - 1; i >= 0; i--) {
            if (this.height - this.area[i] > 0) {
                if (endPlace === undefined) {
                    endPlace = i;
                }
                else {
                    if (i < this.area.length - 1 && this.area[i] <= this.area[i + 1]) {
                        startPlace = i;
                    }
                    else {
                        break;
                    }
                }
            }
            else {
                break;
            }
        }
        if (startPlace !== undefined && endPlace !== undefined && endPlace - startPlace >= panelWidth - 1) {
            var yPos = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.max(this.area.slice(startPlace));
            place = {
                x: startPlace,
                y: yPos,
            };
        }
        else if (!callOnce) {
            // wrap to next row
            this.yPos += this.height;
            this.reset();
            return this.getPanelPosition(panelHeight, panelWidth, true);
        }
        else {
            return null;
        }
        return place;
    };
    return RowArea;
}());
function upgradePanelLink(link) {
    var url = link.url;
    if (!url && link.dashboard) {
        url = "/dashboard/db/" + app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_4__["default"].slugifyForUrl(link.dashboard);
    }
    if (!url && link.dashUri) {
        url = "/dashboard/" + link.dashUri;
    }
    // some models are incomplete and have no dashboard or dashUri
    if (!url) {
        url = '/';
    }
    if (link.keepTime) {
        url = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["appendQueryToUrl"])(url, "$" + _grafana_ui__WEBPACK_IMPORTED_MODULE_7__["DataLinkBuiltInVars"].keepTime);
    }
    if (link.includeVars) {
        url = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["appendQueryToUrl"])(url, "$" + _grafana_ui__WEBPACK_IMPORTED_MODULE_7__["DataLinkBuiltInVars"].includeVars);
    }
    if (link.params) {
        url = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_3__["appendQueryToUrl"])(url, link.params);
    }
    return {
        url: url,
        title: link.title,
        targetBlank: link.targetBlank,
    };
}
function updateVariablesSyntax(text) {
    var legacyVariableNamesRegex = /(__series_name)|(\$__series_name)|(__value_time)|(__field_name)|(\$__field_name)/g;
    return text.replace(legacyVariableNamesRegex, function (match, seriesName, seriesName1, valueTime, fieldName, fieldName1) {
        if (seriesName) {
            return '__series.name';
        }
        if (seriesName1) {
            return '${__series.name}';
        }
        if (valueTime) {
            return '__value.time';
        }
        if (fieldName) {
            return '__field.name';
        }
        if (fieldName1) {
            return '${__field.name}';
        }
        return match;
    });
}


/***/ }),

/***/ "./public/app/features/dashboard/state/DashboardModel.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/dashboard/state/DashboardModel.ts ***!
  \***************************************************************/
/*! exports provided: DashboardModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardModel", function() { return DashboardModel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/constants */ "./public/app/core/constants.ts");
/* harmony import */ var app_core_utils_emitter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/emitter */ "./public/app/core/utils/emitter.ts");
/* harmony import */ var app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/services/context_srv */ "./public/app/core/services/context_srv.ts");
/* harmony import */ var app_core_utils_sort_by_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/utils/sort_by_keys */ "./public/app/core/utils/sort_by_keys.ts");
/* harmony import */ var _PanelModel__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./PanelModel */ "./public/app/features/dashboard/state/PanelModel.ts");
/* harmony import */ var _DashboardMigrator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./DashboardMigrator */ "./public/app/features/dashboard/state/DashboardMigrator.ts");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libaries

// Constants


// Utils & Services



// Types




var DashboardModel = /** @class */ (function () {
    function DashboardModel(data, meta) {
        if (!data) {
            data = {};
        }
        this.events = new app_core_utils_emitter__WEBPACK_IMPORTED_MODULE_4__["Emitter"]();
        this.id = data.id || null;
        this.uid = data.uid || null;
        this.revision = data.revision;
        this.title = data.title || 'No Title';
        this.autoUpdate = data.autoUpdate;
        this.description = data.description;
        this.tags = data.tags || [];
        this.style = data.style || 'dark';
        this.timezone = data.timezone || '';
        this.editable = data.editable !== false;
        this.graphTooltip = data.graphTooltip || 0;
        this.time = data.time || { from: 'now-6h', to: 'now' };
        this.timepicker = data.timepicker || {};
        this.templating = this.ensureListExist(data.templating);
        this.annotations = this.ensureListExist(data.annotations);
        this.refresh = data.refresh;
        this.snapshot = data.snapshot;
        this.schemaVersion = data.schemaVersion || 0;
        this.version = data.version || 0;
        this.links = data.links || [];
        this.gnetId = data.gnetId || null;
        this.panels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(data.panels || [], function (panelData) { return new _PanelModel__WEBPACK_IMPORTED_MODULE_7__["PanelModel"](panelData); });
        this.resetOriginalVariables();
        this.resetOriginalTime();
        this.initMeta(meta);
        this.updateSchema(data);
        this.addBuiltInAnnotationQuery();
        this.sortPanelsByGridPos();
    }
    DashboardModel.prototype.addBuiltInAnnotationQuery = function () {
        var e_1, _a;
        var found = false;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.annotations.list), _c = _b.next(); !_c.done; _c = _b.next()) {
                var item = _c.value;
                if (item.builtIn === 1) {
                    found = true;
                    break;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        if (found) {
            return;
        }
        this.annotations.list.unshift({
            datasource: '-- Grafana --',
            name: 'Annotations & Alerts',
            type: 'dashboard',
            iconColor: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DEFAULT_ANNOTATION_COLOR"],
            enable: true,
            hide: true,
            builtIn: 1,
        });
    };
    DashboardModel.prototype.initMeta = function (meta) {
        meta = meta || {};
        meta.canShare = meta.canShare !== false;
        meta.canSave = meta.canSave !== false;
        meta.canStar = meta.canStar !== false;
        meta.canEdit = meta.canEdit !== false;
        meta.showSettings = meta.canEdit;
        meta.canMakeEditable = meta.canSave && !this.editable;
        meta.fullscreen = false;
        meta.isEditing = false;
        if (!this.editable) {
            meta.canEdit = false;
            meta.canDelete = false;
            meta.canSave = false;
        }
        this.meta = meta;
    };
    // cleans meta data and other non persistent state
    DashboardModel.prototype.getSaveModelClone = function (options) {
        var defaults = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(options || {}, {
            saveVariables: true,
            saveTimerange: true,
        });
        // make clone
        var copy = {};
        for (var property in this) {
            if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
                continue;
            }
            copy[property] = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(this[property]);
        }
        // get variable save models
        copy.templating = {
            list: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.templating.list, function (variable) {
                return variable.getSaveModel ? variable.getSaveModel() : variable;
            }),
        };
        if (!defaults.saveVariables) {
            for (var i = 0; i < copy.templating.list.length; i++) {
                var current = copy.templating.list[i];
                var original = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.originalTemplating, { name: current.name, type: current.type });
                if (!original) {
                    continue;
                }
                if (current.type === 'adhoc') {
                    copy.templating.list[i].filters = original.filters;
                }
                else {
                    copy.templating.list[i].current = original.current;
                }
            }
        }
        if (!defaults.saveTimerange) {
            copy.time = this.originalTime;
        }
        // get panel save models
        copy.panels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.chain(this.panels)
            .filter(function (panel) { return panel.type !== 'add-panel'; })
            .map(function (panel) { return panel.getSaveModel(); })
            .value();
        //  sort by keys
        copy = Object(app_core_utils_sort_by_keys__WEBPACK_IMPORTED_MODULE_6__["default"])(copy);
        return copy;
    };
    DashboardModel.prototype.setViewMode = function (panel, fullscreen, isEditing) {
        this.meta.fullscreen = fullscreen;
        this.meta.isEditing = isEditing && this.meta.canEdit;
        panel.setViewMode(fullscreen, this.meta.isEditing);
        this.events.emit('view-mode-changed', panel);
    };
    DashboardModel.prototype.timeRangeUpdated = function (timeRange) {
        this.events.emit('time-range-updated', timeRange);
    };
    DashboardModel.prototype.startRefresh = function () {
        var e_2, _a;
        this.events.emit('refresh');
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                var panel = _c.value;
                if (!this.otherPanelInFullscreen(panel)) {
                    panel.refresh();
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
    };
    DashboardModel.prototype.render = function () {
        var e_3, _a;
        this.events.emit('render');
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                var panel = _c.value;
                panel.render();
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
    };
    DashboardModel.prototype.panelInitialized = function (panel) {
        panel.initialized();
        if (!this.otherPanelInFullscreen(panel)) {
            panel.refresh();
        }
    };
    DashboardModel.prototype.otherPanelInFullscreen = function (panel) {
        return this.meta.fullscreen && !panel.fullscreen;
    };
    DashboardModel.prototype.ensureListExist = function (data) {
        if (!data) {
            data = {};
        }
        if (!data.list) {
            data.list = [];
        }
        return data;
    };
    DashboardModel.prototype.getNextPanelId = function () {
        var e_4, _a, e_5, _b;
        var max = 0;
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _d = _c.next(); !_d.done; _d = _c.next()) {
                var panel = _d.value;
                if (panel.id > max) {
                    max = panel.id;
                }
                if (panel.collapsed) {
                    try {
                        for (var _e = (e_5 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.panels)), _f = _e.next(); !_f.done; _f = _e.next()) {
                            var rowPanel = _f.value;
                            if (rowPanel.id > max) {
                                max = rowPanel.id;
                            }
                        }
                    }
                    catch (e_5_1) { e_5 = { error: e_5_1 }; }
                    finally {
                        try {
                            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                        }
                        finally { if (e_5) throw e_5.error; }
                    }
                }
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_4) throw e_4.error; }
        }
        return max + 1;
    };
    DashboardModel.prototype.forEachPanel = function (callback) {
        for (var i = 0; i < this.panels.length; i++) {
            callback(this.panels[i], i);
        }
    };
    DashboardModel.prototype.getPanelById = function (id) {
        var e_6, _a;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                var panel = _c.value;
                if (panel.id === id) {
                    return panel;
                }
            }
        }
        catch (e_6_1) { e_6 = { error: e_6_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_6) throw e_6.error; }
        }
        return null;
    };
    DashboardModel.prototype.addPanel = function (panelData) {
        panelData.id = this.getNextPanelId();
        var panel = new _PanelModel__WEBPACK_IMPORTED_MODULE_7__["PanelModel"](panelData);
        this.panels.unshift(panel);
        this.sortPanelsByGridPos();
        this.events.emit('panel-added', panel);
    };
    DashboardModel.prototype.sortPanelsByGridPos = function () {
        this.panels.sort(function (panelA, panelB) {
            if (panelA.gridPos.y === panelB.gridPos.y) {
                return panelA.gridPos.x - panelB.gridPos.x;
            }
            else {
                return panelA.gridPos.y - panelB.gridPos.y;
            }
        });
    };
    DashboardModel.prototype.cleanUpRepeats = function () {
        var e_7, _a;
        if (this.snapshot || this.templating.list.length === 0) {
            return;
        }
        this.iteration = (this.iteration || new Date().getTime()) + 1;
        var panelsToRemove = [];
        try {
            // cleanup scopedVars
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                var panel = _c.value;
                delete panel.scopedVars;
            }
        }
        catch (e_7_1) { e_7 = { error: e_7_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_7) throw e_7.error; }
        }
        for (var i = 0; i < this.panels.length; i++) {
            var panel = this.panels[i];
            if ((!panel.repeat || panel.repeatedByRow) && panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
                panelsToRemove.push(panel);
            }
        }
        // remove panels
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.pull.apply(lodash__WEBPACK_IMPORTED_MODULE_1___default.a, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([this.panels], panelsToRemove));
        panelsToRemove.map(function (p) { return p.destroy(); });
        this.sortPanelsByGridPos();
        this.events.emit('repeats-processed');
    };
    DashboardModel.prototype.processRepeats = function () {
        if (this.snapshot || this.templating.list.length === 0) {
            return;
        }
        this.cleanUpRepeats();
        this.iteration = (this.iteration || new Date().getTime()) + 1;
        for (var i = 0; i < this.panels.length; i++) {
            var panel = this.panels[i];
            if (panel.repeat) {
                this.repeatPanel(panel, i);
            }
        }
        this.sortPanelsByGridPos();
        this.events.emit('repeats-processed');
    };
    DashboardModel.prototype.cleanUpRowRepeats = function (rowPanels) {
        var panelsToRemove = [];
        for (var i = 0; i < rowPanels.length; i++) {
            var panel = rowPanels[i];
            if (!panel.repeat && panel.repeatPanelId) {
                panelsToRemove.push(panel);
            }
        }
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.pull.apply(lodash__WEBPACK_IMPORTED_MODULE_1___default.a, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([rowPanels], panelsToRemove));
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.pull.apply(lodash__WEBPACK_IMPORTED_MODULE_1___default.a, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([this.panels], panelsToRemove));
    };
    DashboardModel.prototype.processRowRepeats = function (row) {
        if (this.snapshot || this.templating.list.length === 0) {
            return;
        }
        var rowPanels = row.panels;
        if (!row.collapsed) {
            var rowPanelIndex = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.findIndex(this.panels, function (p) { return p.id === row.id; });
            rowPanels = this.getRowPanels(rowPanelIndex);
        }
        this.cleanUpRowRepeats(rowPanels);
        var _loop_1 = function (i) {
            var panel = rowPanels[i];
            if (panel.repeat) {
                var panelIndex = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.findIndex(this_1.panels, function (p) { return p.id === panel.id; });
                this_1.repeatPanel(panel, panelIndex);
            }
        };
        var this_1 = this;
        for (var i = 0; i < rowPanels.length; i++) {
            _loop_1(i);
        }
    };
    DashboardModel.prototype.getPanelRepeatClone = function (sourcePanel, valueIndex, sourcePanelIndex) {
        // if first clone return source
        if (valueIndex === 0) {
            return sourcePanel;
        }
        var clone = new _PanelModel__WEBPACK_IMPORTED_MODULE_7__["PanelModel"](sourcePanel.getSaveModel());
        clone.id = this.getNextPanelId();
        // insert after source panel + value index
        this.panels.splice(sourcePanelIndex + valueIndex, 0, clone);
        clone.repeatIteration = this.iteration;
        clone.repeatPanelId = sourcePanel.id;
        clone.repeat = null;
        return clone;
    };
    DashboardModel.prototype.getRowRepeatClone = function (sourceRowPanel, valueIndex, sourcePanelIndex) {
        // if first clone return source
        if (valueIndex === 0) {
            if (!sourceRowPanel.collapsed) {
                var rowPanels_1 = this.getRowPanels(sourcePanelIndex);
                sourceRowPanel.panels = rowPanels_1;
            }
            return sourceRowPanel;
        }
        var clone = new _PanelModel__WEBPACK_IMPORTED_MODULE_7__["PanelModel"](sourceRowPanel.getSaveModel());
        // for row clones we need to figure out panels under row to clone and where to insert clone
        var rowPanels, insertPos;
        if (sourceRowPanel.collapsed) {
            rowPanels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(sourceRowPanel.panels);
            clone.panels = rowPanels;
            // insert copied row after preceding row
            insertPos = sourcePanelIndex + valueIndex;
        }
        else {
            rowPanels = this.getRowPanels(sourcePanelIndex);
            clone.panels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(rowPanels, function (panel) { return panel.getSaveModel(); });
            // insert copied row after preceding row's panels
            insertPos = sourcePanelIndex + (rowPanels.length + 1) * valueIndex;
        }
        this.panels.splice(insertPos, 0, clone);
        this.updateRepeatedPanelIds(clone);
        return clone;
    };
    DashboardModel.prototype.repeatPanel = function (panel, panelIndex) {
        var variable = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(this.templating.list, { name: panel.repeat });
        if (!variable) {
            return;
        }
        if (panel.type === 'row') {
            this.repeatRow(panel, panelIndex, variable);
            return;
        }
        var selectedOptions = this.getSelectedVariableOptions(variable);
        var maxPerRow = panel.maxPerRow || 4;
        var xPos = 0;
        var yPos = panel.gridPos.y;
        for (var index = 0; index < selectedOptions.length; index++) {
            var option = selectedOptions[index];
            var copy = void 0;
            copy = this.getPanelRepeatClone(panel, index, panelIndex);
            copy.scopedVars = copy.scopedVars || {};
            copy.scopedVars[variable.name] = option;
            if (panel.repeatDirection === app_core_constants__WEBPACK_IMPORTED_MODULE_3__["REPEAT_DIR_VERTICAL"]) {
                if (index > 0) {
                    yPos += copy.gridPos.h;
                }
                copy.gridPos.y = yPos;
            }
            else {
                // set width based on how many are selected
                // assumed the repeated panels should take up full row width
                copy.gridPos.w = Math.max(app_core_constants__WEBPACK_IMPORTED_MODULE_3__["GRID_COLUMN_COUNT"] / selectedOptions.length, app_core_constants__WEBPACK_IMPORTED_MODULE_3__["GRID_COLUMN_COUNT"] / maxPerRow);
                copy.gridPos.x = xPos;
                copy.gridPos.y = yPos;
                xPos += copy.gridPos.w;
                // handle overflow by pushing down one row
                if (xPos + copy.gridPos.w > app_core_constants__WEBPACK_IMPORTED_MODULE_3__["GRID_COLUMN_COUNT"]) {
                    xPos = 0;
                    yPos += copy.gridPos.h;
                }
            }
        }
        // Update gridPos for panels below
        var yOffset = yPos - panel.gridPos.y;
        if (yOffset > 0) {
            var panelBelowIndex = panelIndex + selectedOptions.length;
            for (var i = panelBelowIndex; i < this.panels.length; i++) {
                this.panels[i].gridPos.y += yOffset;
            }
        }
    };
    DashboardModel.prototype.repeatRow = function (panel, panelIndex, variable) {
        var _this = this;
        var selectedOptions = this.getSelectedVariableOptions(variable);
        var yPos = panel.gridPos.y;
        function setScopedVars(panel, variableOption) {
            panel.scopedVars = panel.scopedVars || {};
            panel.scopedVars[variable.name] = variableOption;
        }
        var _loop_2 = function (optionIndex) {
            var option = selectedOptions[optionIndex];
            var rowCopy = this_2.getRowRepeatClone(panel, optionIndex, panelIndex);
            setScopedVars(rowCopy, option);
            var rowHeight = this_2.getRowHeight(rowCopy);
            var rowPanels = rowCopy.panels || [];
            var panelBelowIndex = void 0;
            if (panel.collapsed) {
                // For collapsed row just copy its panels and set scoped vars and proper IDs
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(rowPanels, function (rowPanel, i) {
                    setScopedVars(rowPanel, option);
                    if (optionIndex > 0) {
                        _this.updateRepeatedPanelIds(rowPanel, true);
                    }
                });
                rowCopy.gridPos.y += optionIndex;
                yPos += optionIndex;
                panelBelowIndex = panelIndex + optionIndex + 1;
            }
            else {
                // insert after 'row' panel
                var insertPos_1 = panelIndex + (rowPanels.length + 1) * optionIndex + 1;
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(rowPanels, function (rowPanel, i) {
                    setScopedVars(rowPanel, option);
                    if (optionIndex > 0) {
                        var cloneRowPanel = new _PanelModel__WEBPACK_IMPORTED_MODULE_7__["PanelModel"](rowPanel);
                        _this.updateRepeatedPanelIds(cloneRowPanel, true);
                        // For exposed row additionally set proper Y grid position and add it to dashboard panels
                        cloneRowPanel.gridPos.y += rowHeight * optionIndex;
                        _this.panels.splice(insertPos_1 + i, 0, cloneRowPanel);
                    }
                });
                rowCopy.panels = [];
                rowCopy.gridPos.y += rowHeight * optionIndex;
                yPos += rowHeight;
                panelBelowIndex = insertPos_1 + rowPanels.length;
            }
            // Update gridPos for panels below
            for (var i = panelBelowIndex; i < this_2.panels.length; i++) {
                this_2.panels[i].gridPos.y += yPos;
            }
        };
        var this_2 = this;
        for (var optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
            _loop_2(optionIndex);
        }
    };
    DashboardModel.prototype.updateRepeatedPanelIds = function (panel, repeatedByRow) {
        panel.repeatPanelId = panel.id;
        panel.id = this.getNextPanelId();
        panel.repeatIteration = this.iteration;
        if (repeatedByRow) {
            panel.repeatedByRow = true;
        }
        else {
            panel.repeat = null;
        }
        return panel;
    };
    DashboardModel.prototype.getSelectedVariableOptions = function (variable) {
        var selectedOptions;
        if (variable.current.text === 'All') {
            selectedOptions = variable.options.slice(1, variable.options.length);
        }
        else {
            selectedOptions = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(variable.options, { selected: true });
        }
        return selectedOptions;
    };
    DashboardModel.prototype.getRowHeight = function (rowPanel) {
        if (!rowPanel.panels || rowPanel.panels.length === 0) {
            return 0;
        }
        var rowYPos = rowPanel.gridPos.y;
        var positions = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(rowPanel.panels, 'gridPos');
        var maxPos = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.maxBy(positions, function (pos) {
            return pos.y + pos.h;
        });
        return maxPos.y + maxPos.h - rowYPos;
    };
    DashboardModel.prototype.removePanel = function (panel) {
        var index = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.panels, panel);
        this.panels.splice(index, 1);
        this.events.emit('panel-removed', panel);
    };
    DashboardModel.prototype.removeRow = function (row, removePanels) {
        var needToogle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
        if (needToogle) {
            this.toggleRow(row);
        }
        this.removePanel(row);
    };
    DashboardModel.prototype.expandRows = function () {
        for (var i = 0; i < this.panels.length; i++) {
            var panel = this.panels[i];
            if (panel.type !== 'row') {
                continue;
            }
            if (panel.collapsed) {
                this.toggleRow(panel);
            }
        }
    };
    DashboardModel.prototype.collapseRows = function () {
        for (var i = 0; i < this.panels.length; i++) {
            var panel = this.panels[i];
            if (panel.type !== 'row') {
                continue;
            }
            if (!panel.collapsed) {
                this.toggleRow(panel);
            }
        }
    };
    DashboardModel.prototype.setPanelFocus = function (id) {
        this.meta.focusPanelId = id;
    };
    DashboardModel.prototype.updateSubmenuVisibility = function () {
        var _this = this;
        this.meta.submenuEnabled = (function () {
            if (_this.links.length > 0) {
                return true;
            }
            var visibleVars = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(_this.templating.list, function (variable) { return variable.hide !== 2; });
            if (visibleVars.length > 0) {
                return true;
            }
            var visibleAnnotations = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(_this.annotations.list, function (annotation) { return annotation.hide !== true; });
            if (visibleAnnotations.length > 0) {
                return true;
            }
            return false;
        })();
    };
    DashboardModel.prototype.getPanelInfoById = function (panelId) {
        for (var i = 0; i < this.panels.length; i++) {
            if (this.panels[i].id === panelId) {
                return {
                    panel: this.panels[i],
                    index: i,
                };
            }
        }
        return null;
    };
    DashboardModel.prototype.duplicatePanel = function (panel) {
        var newPanel = panel.getSaveModel();
        newPanel.id = this.getNextPanelId();
        delete newPanel.repeat;
        delete newPanel.repeatIteration;
        delete newPanel.repeatPanelId;
        delete newPanel.scopedVars;
        if (newPanel.alert) {
            delete newPanel.thresholds;
        }
        delete newPanel.alert;
        // does it fit to the right?
        if (panel.gridPos.x + panel.gridPos.w * 2 <= app_core_constants__WEBPACK_IMPORTED_MODULE_3__["GRID_COLUMN_COUNT"]) {
            newPanel.gridPos.x += panel.gridPos.w;
        }
        else {
            // add below
            newPanel.gridPos.y += panel.gridPos.h;
        }
        this.addPanel(newPanel);
        return newPanel;
    };
    DashboardModel.prototype.formatDate = function (date, format) {
        date = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["isDateTime"])(date) ? date : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["dateTime"])(date);
        format = format || 'YYYY-MM-DD HH:mm:ss';
        var timezone = this.getTimezone();
        return timezone === 'browser' ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["dateTime"])(date).format(format) : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["toUtc"])(date).format(format);
    };
    DashboardModel.prototype.destroy = function () {
        var e_8, _a;
        this.events.removeAllListeners();
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                var panel = _c.value;
                panel.destroy();
            }
        }
        catch (e_8_1) { e_8 = { error: e_8_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_8) throw e_8.error; }
        }
    };
    DashboardModel.prototype.toggleRow = function (row) {
        var e_9, _a;
        var rowIndex = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.panels, row);
        if (row.collapsed) {
            row.collapsed = false;
            var hasRepeat = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.some(row.panels, function (p) { return p.repeat; });
            if (row.panels.length > 0) {
                // Use first panel to figure out if it was moved or pushed
                var firstPanel = row.panels[0];
                var yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h);
                // start inserting after row
                var insertPos = rowIndex + 1;
                // y max will represent the bottom y pos after all panels have been added
                // needed to know home much panels below should be pushed down
                var yMax = row.gridPos.y;
                try {
                    for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](row.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var panel = _c.value;
                        // make sure y is adjusted (in case row moved while collapsed)
                        // console.log('yDiff', yDiff);
                        panel.gridPos.y -= yDiff;
                        // insert after row
                        this.panels.splice(insertPos, 0, new _PanelModel__WEBPACK_IMPORTED_MODULE_7__["PanelModel"](panel));
                        // update insert post and y max
                        insertPos += 1;
                        yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
                    }
                }
                catch (e_9_1) { e_9 = { error: e_9_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_9) throw e_9.error; }
                }
                var pushDownAmount = yMax - row.gridPos.y - 1;
                // push panels below down
                for (var panelIndex = insertPos; panelIndex < this.panels.length; panelIndex++) {
                    this.panels[panelIndex].gridPos.y += pushDownAmount;
                }
                row.panels = [];
                if (hasRepeat) {
                    this.processRowRepeats(row);
                }
            }
            // sort panels
            this.sortPanelsByGridPos();
            // emit change event
            this.events.emit('row-expanded');
            return;
        }
        var rowPanels = this.getRowPanels(rowIndex);
        // remove panels
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.pull.apply(lodash__WEBPACK_IMPORTED_MODULE_1___default.a, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([this.panels], rowPanels));
        // save panel models inside row panel
        row.panels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(rowPanels, function (panel) { return panel.getSaveModel(); });
        row.collapsed = true;
        // emit change event
        this.events.emit('row-collapsed');
    };
    /**
     * Will return all panels after rowIndex until it encounters another row
     */
    DashboardModel.prototype.getRowPanels = function (rowIndex) {
        var rowPanels = [];
        for (var index = rowIndex + 1; index < this.panels.length; index++) {
            var panel = this.panels[index];
            // break when encountering another row
            if (panel.type === 'row') {
                break;
            }
            // this panel must belong to row
            rowPanels.push(panel);
        }
        return rowPanels;
    };
    DashboardModel.prototype.on = function (eventName, callback) {
        this.events.on(eventName, callback);
    };
    DashboardModel.prototype.off = function (eventName, callback) {
        this.events.off(eventName, callback);
    };
    DashboardModel.prototype.cycleGraphTooltip = function () {
        this.graphTooltip = (this.graphTooltip + 1) % 3;
    };
    DashboardModel.prototype.sharedTooltipModeEnabled = function () {
        return this.graphTooltip > 0;
    };
    DashboardModel.prototype.sharedCrosshairModeOnly = function () {
        return this.graphTooltip === 1;
    };
    DashboardModel.prototype.getRelativeTime = function (date) {
        date = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["isDateTime"])(date) ? date : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["dateTime"])(date);
        return this.timezone === 'browser' ? Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["dateTime"])(date).fromNow() : Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["toUtc"])(date).fromNow();
    };
    DashboardModel.prototype.isTimezoneUtc = function () {
        return this.getTimezone() === 'utc';
    };
    DashboardModel.prototype.isSnapshot = function () {
        return this.snapshot !== undefined;
    };
    DashboardModel.prototype.getTimezone = function () {
        return (this.timezone ? this.timezone : app_core_services_context_srv__WEBPACK_IMPORTED_MODULE_5__["contextSrv"].user.timezone);
    };
    DashboardModel.prototype.updateSchema = function (old) {
        var migrator = new _DashboardMigrator__WEBPACK_IMPORTED_MODULE_8__["DashboardMigrator"](this);
        migrator.updateSchema(old);
    };
    DashboardModel.prototype.resetOriginalTime = function () {
        this.originalTime = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(this.time);
    };
    DashboardModel.prototype.hasTimeChanged = function () {
        return !lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(this.time, this.originalTime);
    };
    DashboardModel.prototype.resetOriginalVariables = function () {
        this.originalTemplating = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.templating.list, function (variable) {
            return {
                name: variable.name,
                type: variable.type,
                current: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(variable.current),
                filters: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(variable.filters),
            };
        });
    };
    DashboardModel.prototype.hasVariableValuesChanged = function () {
        if (this.templating.list.length !== this.originalTemplating.length) {
            return false;
        }
        var updated = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(this.templating.list, function (variable) {
            return {
                name: variable.name,
                type: variable.type,
                current: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(variable.current),
                filters: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(variable.filters),
            };
        });
        return !lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(updated, this.originalTemplating);
    };
    DashboardModel.prototype.autoFitPanels = function (viewHeight, kioskMode) {
        var currentGridHeight = Math.max.apply(Math, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](this.panels.map(function (panel) {
            return panel.gridPos.h + panel.gridPos.y;
        })));
        var navbarHeight = 55;
        var margin = 20;
        var submenuHeight = 50;
        var visibleHeight = viewHeight - navbarHeight - margin;
        // Remove submenu height if visible
        if (this.meta.submenuEnabled && !kioskMode) {
            visibleHeight -= submenuHeight;
        }
        // add back navbar height
        if (kioskMode && kioskMode !== app_types__WEBPACK_IMPORTED_MODULE_9__["KIOSK_MODE_TV"]) {
            visibleHeight += navbarHeight;
        }
        var visibleGridHeight = Math.floor(visibleHeight / (app_core_constants__WEBPACK_IMPORTED_MODULE_3__["GRID_CELL_HEIGHT"] + app_core_constants__WEBPACK_IMPORTED_MODULE_3__["GRID_CELL_VMARGIN"]));
        var scaleFactor = currentGridHeight / visibleGridHeight;
        this.panels.forEach(function (panel, i) {
            panel.gridPos.y = Math.round(panel.gridPos.y / scaleFactor) || 1;
            panel.gridPos.h = Math.round(panel.gridPos.h / scaleFactor) || 1;
        });
    };
    DashboardModel.prototype.templateVariableValueUpdated = function () {
        this.processRepeats();
        this.events.emit('template-variable-value-updated');
    };
    DashboardModel.prototype.expandParentRowFor = function (panelId) {
        var e_10, _a, e_11, _b;
        try {
            for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.panels), _d = _c.next(); !_d.done; _d = _c.next()) {
                var panel = _d.value;
                if (panel.collapsed) {
                    try {
                        for (var _e = (e_11 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.panels)), _f = _e.next(); !_f.done; _f = _e.next()) {
                            var rowPanel = _f.value;
                            if (rowPanel.id === panelId) {
                                this.toggleRow(panel);
                                return;
                            }
                        }
                    }
                    catch (e_11_1) { e_11 = { error: e_11_1 }; }
                    finally {
                        try {
                            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                        }
                        finally { if (e_11) throw e_11.error; }
                    }
                }
            }
        }
        catch (e_10_1) { e_10 = { error: e_10_1 }; }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
            }
            finally { if (e_10) throw e_10.error; }
        }
    };
    DashboardModel.prototype.toggleLegendsForAll = function () {
        var e_12, _a;
        var panelsWithLegends = this.panels.filter(function (panel) {
            return panel.legend !== undefined && panel.legend !== null;
        });
        // determine if more panels are displaying legends or not
        var onCount = panelsWithLegends.filter(function (panel) { return panel.legend.show; }).length;
        var offCount = panelsWithLegends.length - onCount;
        var panelLegendsOn = onCount >= offCount;
        try {
            for (var panelsWithLegends_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panelsWithLegends), panelsWithLegends_1_1 = panelsWithLegends_1.next(); !panelsWithLegends_1_1.done; panelsWithLegends_1_1 = panelsWithLegends_1.next()) {
                var panel = panelsWithLegends_1_1.value;
                panel.legend.show = !panelLegendsOn;
                panel.render();
            }
        }
        catch (e_12_1) { e_12 = { error: e_12_1 }; }
        finally {
            try {
                if (panelsWithLegends_1_1 && !panelsWithLegends_1_1.done && (_a = panelsWithLegends_1.return)) _a.call(panelsWithLegends_1);
            }
            finally { if (e_12) throw e_12.error; }
        }
    };
    DashboardModel.nonPersistedProperties = {
        events: true,
        meta: true,
        panels: true,
        templating: true,
        originalTime: true,
        originalTemplating: true,
    };
    return DashboardModel;
}());



/***/ }),

/***/ "./public/app/features/dashboard/state/PanelModel.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/dashboard/state/PanelModel.ts ***!
  \***********************************************************/
/*! exports provided: PanelModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelModel", function() { return PanelModel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_emitter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/emitter */ "./public/app/core/utils/emitter.ts");
/* harmony import */ var app_core_utils_query__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/query */ "./public/app/core/utils/query.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _PanelQueryRunner__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./PanelQueryRunner */ "./public/app/features/dashboard/state/PanelQueryRunner.ts");

// Libraries

// Utils




var notPersistedProperties = {
    events: true,
    fullscreen: true,
    isEditing: true,
    isInView: true,
    hasRefreshed: true,
    cachedPluginOptions: true,
    plugin: true,
    queryRunner: true,
};
// For angular panels we need to clean up properties when changing type
// To make sure the change happens without strange bugs happening when panels use same
// named property with different type / value expectations
// This is not required for react panels
var mustKeepProps = {
    id: true,
    gridPos: true,
    type: true,
    title: true,
    scopedVars: true,
    repeat: true,
    repeatIteration: true,
    repeatPanelId: true,
    repeatDirection: true,
    repeatedByRow: true,
    minSpan: true,
    collapsed: true,
    panels: true,
    targets: true,
    datasource: true,
    timeFrom: true,
    timeShift: true,
    hideTimeOverride: true,
    description: true,
    links: true,
    fullscreen: true,
    isEditing: true,
    hasRefreshed: true,
    events: true,
    cacheTimeout: true,
    cachedPluginOptions: true,
    transparent: true,
    pluginVersion: true,
    queryRunner: true,
    transformations: true,
};
var defaults = {
    gridPos: { x: 0, y: 0, h: 3, w: 6 },
    targets: [{ refId: 'A' }],
    cachedPluginOptions: {},
    transparent: false,
};
var PanelModel = /** @class */ (function () {
    function PanelModel(model) {
        this.events = new app_core_utils_emitter__WEBPACK_IMPORTED_MODULE_2__["Emitter"]();
        // should not be part of defaults as defaults are removed in save model and
        // this should not be removed in save model as exporter needs to templatize it
        this.datasource = null;
        // copy properties from persisted model
        for (var property in model) {
            this[property] = model[property];
        }
        // defaults
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaultsDeep(this, lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(defaults));
        // queries must have refId
        this.ensureQueryIds();
    }
    PanelModel.prototype.ensureQueryIds = function () {
        var e_1, _a;
        if (this.targets && lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(this.targets)) {
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.targets), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var query = _c.value;
                    if (!query.refId) {
                        query.refId = Object(app_core_utils_query__WEBPACK_IMPORTED_MODULE_3__["getNextRefIdChar"])(this.targets);
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
    };
    PanelModel.prototype.getOptions = function () {
        return this.options;
    };
    PanelModel.prototype.updateOptions = function (options) {
        this.options = options;
        this.render();
    };
    PanelModel.prototype.getSaveModel = function () {
        var model = {};
        for (var property in this) {
            if (notPersistedProperties[property] || !this.hasOwnProperty(property)) {
                continue;
            }
            if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(this[property], defaults[property])) {
                continue;
            }
            model[property] = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(this[property]);
        }
        return model;
    };
    PanelModel.prototype.setViewMode = function (fullscreen, isEditing) {
        this.fullscreen = fullscreen;
        this.isEditing = isEditing;
        this.events.emit('view-mode-changed');
    };
    PanelModel.prototype.updateGridPos = function (newPos) {
        var sizeChanged = false;
        if (this.gridPos.w !== newPos.w || this.gridPos.h !== newPos.h) {
            sizeChanged = true;
        }
        this.gridPos.x = newPos.x;
        this.gridPos.y = newPos.y;
        this.gridPos.w = newPos.w;
        this.gridPos.h = newPos.h;
        if (sizeChanged) {
            this.events.emit('panel-size-changed');
        }
    };
    PanelModel.prototype.resizeDone = function () {
        this.events.emit('panel-size-changed');
    };
    PanelModel.prototype.refresh = function () {
        this.hasRefreshed = true;
        this.events.emit('refresh');
    };
    PanelModel.prototype.render = function () {
        if (!this.hasRefreshed) {
            this.refresh();
        }
        else {
            this.events.emit('render');
        }
    };
    PanelModel.prototype.initialized = function () {
        this.events.emit('panel-initialized');
    };
    PanelModel.prototype.getOptionsToRemember = function () {
        var _this = this;
        return Object.keys(this).reduce(function (acc, property) {
            var _a;
            if (notPersistedProperties[property] || mustKeepProps[property]) {
                return acc;
            }
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, acc, (_a = {}, _a[property] = _this[property], _a));
        }, {});
    };
    PanelModel.prototype.restorePanelOptions = function (pluginId) {
        var _this = this;
        var prevOptions = this.cachedPluginOptions[pluginId] || {};
        Object.keys(prevOptions).map(function (property) {
            _this[property] = prevOptions[property];
        });
    };
    PanelModel.prototype.applyPluginOptionDefaults = function (plugin) {
        if (plugin.angularConfigCtrl) {
            return;
        }
        this.options = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaultsDeep({}, this.options || {}, plugin.defaults);
    };
    PanelModel.prototype.pluginLoaded = function (plugin) {
        this.plugin = plugin;
        if (plugin.panel && plugin.onPanelMigration) {
            var version = getPluginVersion(plugin);
            if (version !== this.pluginVersion) {
                this.options = plugin.onPanelMigration(this);
                this.pluginVersion = version;
            }
        }
        this.applyPluginOptionDefaults(plugin);
    };
    PanelModel.prototype.changePlugin = function (newPlugin) {
        var e_2, _a;
        var pluginId = newPlugin.meta.id;
        var oldOptions = this.getOptionsToRemember();
        var oldPluginId = this.type;
        var wasAngular = !!this.plugin.angularPanelCtrl;
        // for angular panels we must remove all events and let angular panels do some cleanup
        if (wasAngular) {
            this.destroy();
        }
        try {
            // remove panel type specific  options
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](lodash__WEBPACK_IMPORTED_MODULE_1___default.a.keys(this)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var key = _c.value;
                if (mustKeepProps[key]) {
                    continue;
                }
                delete this[key];
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
        this.cachedPluginOptions[oldPluginId] = oldOptions;
        this.restorePanelOptions(pluginId);
        // Let panel plugins inspect options from previous panel and keep any that it can use
        if (newPlugin.onPanelTypeChanged) {
            var old = {};
            if (wasAngular) {
                old = { angular: oldOptions };
            }
            else if (oldOptions && oldOptions.options) {
                old = oldOptions.options;
            }
            this.options = this.options || {};
            Object.assign(this.options, newPlugin.onPanelTypeChanged(this.options, oldPluginId, old));
        }
        // switch
        this.type = pluginId;
        this.plugin = newPlugin;
        this.applyPluginOptionDefaults(newPlugin);
        if (newPlugin.onPanelMigration) {
            this.pluginVersion = getPluginVersion(newPlugin);
        }
    };
    PanelModel.prototype.addQuery = function (query) {
        query = query || { refId: 'A' };
        query.refId = Object(app_core_utils_query__WEBPACK_IMPORTED_MODULE_3__["getNextRefIdChar"])(this.targets);
        this.targets.push(query);
    };
    PanelModel.prototype.changeQuery = function (query, index) {
        // ensure refId is maintained
        query.refId = this.targets[index].refId;
        // update query in array
        this.targets = this.targets.map(function (item, itemIndex) {
            if (itemIndex === index) {
                return query;
            }
            return item;
        });
    };
    PanelModel.prototype.getQueryRunner = function () {
        if (!this.queryRunner) {
            this.queryRunner = new _PanelQueryRunner__WEBPACK_IMPORTED_MODULE_5__["PanelQueryRunner"]();
            this.setTransformations(this.transformations);
        }
        return this.queryRunner;
    };
    PanelModel.prototype.hasTitle = function () {
        return this.title && this.title.length > 0;
    };
    PanelModel.prototype.isAngularPlugin = function () {
        return this.plugin && !!this.plugin.angularPanelCtrl;
    };
    PanelModel.prototype.destroy = function () {
        this.events.emit('panel-teardown');
        this.events.removeAllListeners();
        if (this.queryRunner) {
            this.queryRunner.destroy();
            this.queryRunner = null;
        }
    };
    PanelModel.prototype.setTransformations = function (transformations) {
        this.transformations = transformations;
        this.getQueryRunner().setTransformations(transformations);
    };
    return PanelModel;
}());

function getPluginVersion(plugin) {
    return plugin && plugin.meta.info.version ? plugin.meta.info.version : app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].buildInfo.version;
}


/***/ }),

/***/ "./public/app/features/dashboard/state/PanelQueryRunner.ts":
/*!*****************************************************************!*\
  !*** ./public/app/features/dashboard/state/PanelQueryRunner.ts ***!
  \*****************************************************************/
/*! exports provided: PanelQueryRunner */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelQueryRunner", function() { return PanelQueryRunner; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm5/index.js");
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm5/operators/index.js");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/plugins/datasource_srv */ "./public/app/features/plugins/datasource_srv.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/features/templating/template_srv */ "./public/app/features/templating/template_srv.ts");
/* harmony import */ var _runRequest__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./runRequest */ "./public/app/features/dashboard/state/runRequest.ts");
/* harmony import */ var _plugins_datasource_dashboard__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../plugins/datasource/dashboard */ "./public/app/plugins/datasource/dashboard/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libraries



// Services & Utils







var counter = 100;
function getNextRequestId() {
    return 'Q' + counter++;
}
var PanelQueryRunner = /** @class */ (function () {
    function PanelQueryRunner() {
        this.subject = new rxjs__WEBPACK_IMPORTED_MODULE_2__["ReplaySubject"](1);
    }
    /**
     * Returns an observable that subscribes to the shared multi-cast subject (that reply last result).
     */
    PanelQueryRunner.prototype.getData = function (transform) {
        var _this = this;
        if (transform === void 0) { transform = true; }
        if (transform) {
            return this.subject.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])(function (data) {
                if (_this.hasTransformations()) {
                    var newSeries = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["transformDataFrame"])(_this.transformations, data.series);
                    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, data, { series: newSeries });
                }
                return data;
            }));
        }
        // Just pass it directly
        return this.subject.pipe();
    };
    PanelQueryRunner.prototype.hasTransformations = function () {
        return app_core_config__WEBPACK_IMPORTED_MODULE_4__["config"].featureToggles.transformations && this.transformations && this.transformations.length > 0;
    };
    PanelQueryRunner.prototype.run = function (options) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var queries, timezone, datasource, panelId, dashboardId, timeRange, timeInfo, cacheTimeout, widthPixels, maxDataPoints, scopedVars, minInterval, request, ds_1, lowerIntervalLimit, norm, err_1;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        queries = options.queries, timezone = options.timezone, datasource = options.datasource, panelId = options.panelId, dashboardId = options.dashboardId, timeRange = options.timeRange, timeInfo = options.timeInfo, cacheTimeout = options.cacheTimeout, widthPixels = options.widthPixels, maxDataPoints = options.maxDataPoints, scopedVars = options.scopedVars, minInterval = options.minInterval;
                        if (Object(_plugins_datasource_dashboard__WEBPACK_IMPORTED_MODULE_9__["isSharedDashboardQuery"])(datasource)) {
                            this.pipeToSubject(Object(_plugins_datasource_dashboard__WEBPACK_IMPORTED_MODULE_9__["runSharedRequest"])(options));
                            return [2 /*return*/];
                        }
                        request = {
                            requestId: getNextRequestId(),
                            timezone: timezone,
                            panelId: panelId,
                            dashboardId: dashboardId,
                            range: timeRange,
                            timeInfo: timeInfo,
                            interval: '',
                            intervalMs: 0,
                            targets: Object(lodash__WEBPACK_IMPORTED_MODULE_1__["cloneDeep"])(queries),
                            maxDataPoints: maxDataPoints || widthPixels,
                            scopedVars: scopedVars || {},
                            cacheTimeout: cacheTimeout,
                            startTime: Date.now(),
                        };
                        // Add deprecated property
                        request.rangeRaw = timeRange.raw;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, getDataSource(datasource, request.scopedVars)];
                    case 2:
                        ds_1 = _a.sent();
                        if (ds_1.meta && !ds_1.meta.hiddenQueries) {
                            request.targets = request.targets.filter(function (q) { return !q.hide; });
                        }
                        // Attach the datasource name to each query
                        request.targets = request.targets.map(function (query) {
                            if (!query.datasource) {
                                query.datasource = ds_1.name;
                            }
                            return query;
                        });
                        lowerIntervalLimit = minInterval ? app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_7__["default"].replace(minInterval, request.scopedVars) : ds_1.interval;
                        norm = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_6__["default"].calculateInterval(timeRange, widthPixels, lowerIntervalLimit);
                        // make shallow copy of scoped vars,
                        // and add built in variables interval and interval_ms
                        request.scopedVars = Object.assign({}, request.scopedVars, {
                            __interval: { text: norm.interval, value: norm.interval },
                            __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs },
                        });
                        request.interval = norm.interval;
                        request.intervalMs = norm.intervalMs;
                        this.pipeToSubject(Object(_runRequest__WEBPACK_IMPORTED_MODULE_8__["runRequest"])(ds_1, request));
                        return [3 /*break*/, 4];
                    case 3:
                        err_1 = _a.sent();
                        console.log('PanelQueryRunner Error', err_1);
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    PanelQueryRunner.prototype.pipeToSubject = function (observable) {
        var _this = this;
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
        this.subscription = observable.subscribe({
            next: function (data) {
                _this.lastResult = Object(_runRequest__WEBPACK_IMPORTED_MODULE_8__["preProcessPanelData"])(data, _this.lastResult);
                _this.subject.next(_this.lastResult);
            },
        });
    };
    PanelQueryRunner.prototype.setTransformations = function (transformations) {
        this.transformations = transformations;
    };
    /**
     * Called when the panel is closed
     */
    PanelQueryRunner.prototype.destroy = function () {
        // Tell anyone listening that we are done
        if (this.subject) {
            this.subject.complete();
        }
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    };
    return PanelQueryRunner;
}());

function getDataSource(datasource, scopedVars) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, Promise, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (datasource && datasource.query) {
                        return [2 /*return*/, datasource];
                    }
                    return [4 /*yield*/, Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_5__["getDatasourceSrv"])().get(datasource, scopedVars)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    });
}


/***/ }),

/***/ "./public/app/features/dashboard/state/actions.ts":
/*!********************************************************!*\
  !*** ./public/app/features/dashboard/state/actions.ts ***!
  \********************************************************/
/*! exports provided: loadDashboardPermissions, dashboardInitFetching, dashboardInitServices, dashboardInitSlow, dashboardInitCompleted, dashboardInitFailed, cleanUpDashboard, getDashboardPermissions, updateDashboardPermission, removeDashboardPermission, addDashboardPermission, importDashboard, removeDashboard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDashboardPermissions", function() { return loadDashboardPermissions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardInitFetching", function() { return dashboardInitFetching; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardInitServices", function() { return dashboardInitServices; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardInitSlow", function() { return dashboardInitSlow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardInitCompleted", function() { return dashboardInitCompleted; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardInitFailed", function() { return dashboardInitFailed; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanUpDashboard", function() { return cleanUpDashboard; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDashboardPermissions", function() { return getDashboardPermissions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateDashboardPermission", function() { return updateDashboardPermission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeDashboardPermission", function() { return removeDashboardPermission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addDashboardPermission", function() { return addDashboardPermission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "importDashboard", function() { return importDashboard; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeDashboard", function() { return removeDashboard; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var app_core_copy_appNotification__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/copy/appNotification */ "./public/app/core/copy/appNotification.ts");
/* harmony import */ var _plugins_state_actions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../plugins/state/actions */ "./public/app/features/plugins/state/actions.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");

// Services & Utils



// Actions


var loadDashboardPermissions = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["actionCreatorFactory"])('LOAD_DASHBOARD_PERMISSIONS').create();
var dashboardInitFetching = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["noPayloadActionCreatorFactory"])('DASHBOARD_INIT_FETCHING').create();
var dashboardInitServices = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["noPayloadActionCreatorFactory"])('DASHBOARD_INIT_SERVICES').create();
var dashboardInitSlow = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["noPayloadActionCreatorFactory"])('SET_DASHBOARD_INIT_SLOW').create();
var dashboardInitCompleted = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["actionCreatorFactory"])('DASHBOARD_INIT_COMLETED').create();
/*
 * Unrecoverable init failure (fetch or model creation failed)
 */
var dashboardInitFailed = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["actionCreatorFactory"])('DASHBOARD_INIT_FAILED').create();
/*
 * When leaving dashboard, resets state
 * */
var cleanUpDashboard = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_2__["noPayloadActionCreatorFactory"])('DASHBOARD_CLEAN_UP').create();
function getDashboardPermissions(id) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var permissions;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/dashboards/id/" + id + "/permissions")];
                case 1:
                    permissions = _a.sent();
                    dispatch(loadDashboardPermissions(permissions));
                    return [2 /*return*/];
            }
        });
    }); };
}
function toUpdateItem(item) {
    return {
        userId: item.userId,
        teamId: item.teamId,
        role: item.role,
        permission: item.permission,
    };
}
function updateDashboardPermission(dashboardId, itemToUpdate, level) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dashboard, itemsToUpdate, _a, _b, item, updated;
        var e_1, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    dashboard = getStore().dashboard;
                    itemsToUpdate = [];
                    try {
                        for (_a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboard.permissions), _b = _a.next(); !_b.done; _b = _a.next()) {
                            item = _b.value;
                            if (item.inherited) {
                                continue;
                            }
                            updated = toUpdateItem(item);
                            // if this is the item we want to update, update it's permission
                            if (itemToUpdate === item) {
                                updated.permission = level;
                            }
                            itemsToUpdate.push(updated);
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/dashboards/id/" + dashboardId + "/permissions", { items: itemsToUpdate })];
                case 1:
                    _d.sent();
                    return [4 /*yield*/, dispatch(getDashboardPermissions(dashboardId))];
                case 2:
                    _d.sent();
                    return [2 /*return*/];
            }
        });
    }); };
}
function removeDashboardPermission(dashboardId, itemToDelete) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dashboard, itemsToUpdate, _a, _b, item;
        var e_2, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    dashboard = getStore().dashboard;
                    itemsToUpdate = [];
                    try {
                        for (_a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboard.permissions), _b = _a.next(); !_b.done; _b = _a.next()) {
                            item = _b.value;
                            if (item.inherited || item === itemToDelete) {
                                continue;
                            }
                            itemsToUpdate.push(toUpdateItem(item));
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/dashboards/id/" + dashboardId + "/permissions", { items: itemsToUpdate })];
                case 1:
                    _d.sent();
                    return [4 /*yield*/, dispatch(getDashboardPermissions(dashboardId))];
                case 2:
                    _d.sent();
                    return [2 /*return*/];
            }
        });
    }); };
}
function addDashboardPermission(dashboardId, newItem) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dashboard, itemsToUpdate, _a, _b, item;
        var e_3, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    dashboard = getStore().dashboard;
                    itemsToUpdate = [];
                    try {
                        for (_a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboard.permissions), _b = _a.next(); !_b.done; _b = _a.next()) {
                            item = _b.value;
                            if (item.inherited) {
                                continue;
                            }
                            itemsToUpdate.push(toUpdateItem(item));
                        }
                    }
                    catch (e_3_1) { e_3 = { error: e_3_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                        }
                        finally { if (e_3) throw e_3.error; }
                    }
                    itemsToUpdate.push({
                        userId: newItem.userId,
                        teamId: newItem.teamId,
                        role: newItem.role,
                        permission: newItem.permission,
                    });
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/dashboards/id/" + dashboardId + "/permissions", { items: itemsToUpdate })];
                case 1:
                    _d.sent();
                    return [4 /*yield*/, dispatch(getDashboardPermissions(dashboardId))];
                case 2:
                    _d.sent();
                    return [2 /*return*/];
            }
        });
    }); };
}
function importDashboard(data, dashboardTitle) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post('/api/dashboards/import', data)];
                case 1:
                    _a.sent();
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_5__["notifyApp"])(Object(app_core_copy_appNotification__WEBPACK_IMPORTED_MODULE_3__["createSuccessNotification"])('Dashboard Imported', dashboardTitle)));
                    dispatch(Object(_plugins_state_actions__WEBPACK_IMPORTED_MODULE_4__["loadPluginDashboards"])());
                    return [2 /*return*/];
            }
        });
    }); };
}
function removeDashboard(uri) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().delete("/api/dashboards/" + uri)];
                case 1:
                    _a.sent();
                    dispatch(Object(_plugins_state_actions__WEBPACK_IMPORTED_MODULE_4__["loadPluginDashboards"])());
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/dashboard/state/reducers.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/dashboard/state/reducers.ts ***!
  \*********************************************************/
/*! exports provided: initialState, dashboardReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardReducer", function() { return dashboardReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./actions */ "./public/app/features/dashboard/state/actions.ts");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var app_core_utils_acl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/acl */ "./public/app/core/utils/acl.ts");
/* harmony import */ var _DashboardModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DashboardModel */ "./public/app/features/dashboard/state/DashboardModel.ts");
/* harmony import */ var _panel_editor_state_reducers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../panel_editor/state/reducers */ "./public/app/features/dashboard/panel_editor/state/reducers.ts");







var initialState = {
    initPhase: app_types__WEBPACK_IMPORTED_MODULE_1__["DashboardInitPhase"].NotStarted,
    isInitSlow: false,
    model: null,
    permissions: [],
};
var dashboardReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_3__["reducerFactory"])(initialState)
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["loadDashboardPermissions"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { permissions: Object(app_core_utils_acl__WEBPACK_IMPORTED_MODULE_4__["processAclItems"])(action.payload) })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["dashboardInitFetching"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { initPhase: app_types__WEBPACK_IMPORTED_MODULE_1__["DashboardInitPhase"].Fetching })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["dashboardInitServices"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { initPhase: app_types__WEBPACK_IMPORTED_MODULE_1__["DashboardInitPhase"].Services })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["dashboardInitSlow"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { isInitSlow: true })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["dashboardInitFailed"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { initPhase: app_types__WEBPACK_IMPORTED_MODULE_1__["DashboardInitPhase"].Failed, isInitSlow: false, initError: action.payload, model: new _DashboardModel__WEBPACK_IMPORTED_MODULE_5__["DashboardModel"]({ title: 'Dashboard init failed' }, { canSave: false, canEdit: false }) })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["dashboardInitCompleted"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { initPhase: app_types__WEBPACK_IMPORTED_MODULE_1__["DashboardInitPhase"].Completed, model: action.payload, isInitSlow: false })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_2__["cleanUpDashboard"],
    mapper: function (state, action) {
        // Destroy current DashboardModel
        // Very important as this removes all dashboard event listeners
        state.model.destroy();
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { initPhase: app_types__WEBPACK_IMPORTED_MODULE_1__["DashboardInitPhase"].NotStarted, model: null, isInitSlow: false, initError: null });
    },
})
    .create();
/* harmony default export */ __webpack_exports__["default"] = ({
    dashboard: dashboardReducer,
    panelEditor: _panel_editor_state_reducers__WEBPACK_IMPORTED_MODULE_6__["panelEditorReducer"],
});


/***/ }),

/***/ "./public/app/features/dashboard/state/runRequest.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/dashboard/state/runRequest.ts ***!
  \***********************************************************/
/*! exports provided: processResponsePacket, runRequest, callQueryMethod, processQueryError, getProcessedDataFrames, preProcessPanelData */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processResponsePacket", function() { return processResponsePacket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runRequest", function() { return runRequest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "callQueryMethod", function() { return callQueryMethod; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processQueryError", function() { return processQueryError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProcessedDataFrames", function() { return getProcessedDataFrames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "preProcessPanelData", function() { return preProcessPanelData; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm5/index.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm5/operators/index.js");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");

// Libraries



// Utils & Services


/*
 * This function should handle composing a PanelData from multiple responses
 */
function processResponsePacket(packet, state) {
    var request = state.panelData.request;
    var packets = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.packets);
    packets[packet.key || 'A'] = packet;
    // Update the time range
    var range = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, request.range);
    var timeRange = Object(lodash__WEBPACK_IMPORTED_MODULE_2__["isString"])(range.raw.from)
        ? {
            from: _grafana_data__WEBPACK_IMPORTED_MODULE_5__["dateMath"].parse(range.raw.from, false),
            to: _grafana_data__WEBPACK_IMPORTED_MODULE_5__["dateMath"].parse(range.raw.to, true),
            raw: range.raw,
        }
        : range;
    var combinedData = Object(lodash__WEBPACK_IMPORTED_MODULE_2__["flatten"])(Object(lodash__WEBPACK_IMPORTED_MODULE_2__["map"])(packets, function (packet) {
        return packet.data;
    }));
    var panelData = {
        state: packet.state || _grafana_data__WEBPACK_IMPORTED_MODULE_5__["LoadingState"].Done,
        series: combinedData,
        request: request,
        timeRange: timeRange,
    };
    return { packets: packets, panelData: panelData };
}
/**
 * This function handles the excecution of requests & and processes the single or multiple response packets into
 * a combined PanelData response.
 * It will
 *  * Merge multiple responses into a single DataFrame array based on the packet key
 *  * Will emit a loading state if no response after 50ms
 *  * Cancel any still runnning network requests on unsubscribe (using request.requestId)
 */
function runRequest(datasource, request) {
    var state = {
        panelData: {
            state: _grafana_data__WEBPACK_IMPORTED_MODULE_5__["LoadingState"].Loading,
            series: [],
            request: request,
            timeRange: request.range,
        },
        packets: {},
    };
    // Return early if there are no queries to run
    if (!request.targets.length) {
        request.endTime = Date.now();
        state.panelData.state = _grafana_data__WEBPACK_IMPORTED_MODULE_5__["LoadingState"].Done;
        return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["of"])(state.panelData);
    }
    var dataObservable = callQueryMethod(datasource, request).pipe(
    // Transform response packets into PanelData with merged results
    Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["map"])(function (packet) {
        if (!Object(lodash__WEBPACK_IMPORTED_MODULE_2__["isArray"])(packet.data)) {
            throw new Error("Expected response data to be array, got " + typeof packet.data + ".");
        }
        request.endTime = Date.now();
        state = processResponsePacket(packet, state);
        return state.panelData;
    }), 
    // handle errors
    Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["catchError"])(function (err) {
        return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["of"])(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.panelData, { state: _grafana_data__WEBPACK_IMPORTED_MODULE_5__["LoadingState"].Error, error: processQueryError(err) }));
    }), 
    // finalize is triggered when subscriber unsubscribes
    // This makes sure any still running network requests are cancelled
    Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["finalize"])(cancelNetworkRequestsOnUnsubscribe(request)), 
    // this makes it possible to share this observable in takeUntil
    Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["share"])());
    // If 50ms without a response emit a loading state
    // mapTo will translate the timer event into state.panelData (which has state set to loading)
    // takeUntil will cancel the timer emit when first response packet is received on the dataObservable
    return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["merge"])(Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["timer"])(200).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["mapTo"])(state.panelData), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__["takeUntil"])(dataObservable)), dataObservable);
}
function cancelNetworkRequestsOnUnsubscribe(req) {
    return function () {
        Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__["getBackendSrv"])().resolveCancelerIfExists(req.requestId);
    };
}
function callQueryMethod(datasource, request) {
    var returnVal = datasource.query(request);
    return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["from"])(returnVal);
}
function processQueryError(err) {
    var error = (err || {});
    if (!error.message) {
        if (typeof err === 'string' || err instanceof String) {
            return { message: err };
        }
        var message = 'Query error';
        if (error.message) {
            message = error.message;
        }
        else if (error.data && error.data.message) {
            message = error.data.message;
        }
        else if (error.data && error.data.error) {
            message = error.data.error;
        }
        else if (error.status) {
            message = "Query error: " + error.status + " " + error.statusText;
        }
        error.message = message;
    }
    return error;
}
/**
 * All panels will be passed tables that have our best guess at colum type set
 *
 * This is also used by PanelChrome for snapshot support
 */
function getProcessedDataFrames(results) {
    var e_1, _a, e_2, _b;
    if (!Object(lodash__WEBPACK_IMPORTED_MODULE_2__["isArray"])(results)) {
        return [];
    }
    var dataFrames = [];
    try {
        for (var results_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](results), results_1_1 = results_1.next(); !results_1_1.done; results_1_1 = results_1.next()) {
            var result = results_1_1.value;
            var dataFrame = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["guessFieldTypes"])(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["toDataFrame"])(result));
            try {
                // clear out any cached calcs
                for (var _c = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dataFrame.fields)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var field = _d.value;
                    field.calcs = null;
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                }
                finally { if (e_2) throw e_2.error; }
            }
            dataFrames.push(dataFrame);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (results_1_1 && !results_1_1.done && (_a = results_1.return)) _a.call(results_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return dataFrames;
}
function preProcessPanelData(data, lastResult) {
    var series = data.series;
    //  for loading states with no data, use last result
    if (data.state === _grafana_data__WEBPACK_IMPORTED_MODULE_5__["LoadingState"].Loading && series.length === 0) {
        if (!lastResult) {
            lastResult = data;
        }
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, lastResult, { state: _grafana_data__WEBPACK_IMPORTED_MODULE_5__["LoadingState"].Loading });
    }
    // Make sure the data frames are properly formatted
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, data, { series: getProcessedDataFrames(series) });
}


/***/ }),

/***/ "./public/app/features/dashboard/utils/panel.ts":
/*!******************************************************!*\
  !*** ./public/app/features/dashboard/utils/panel.ts ***!
  \******************************************************/
/*! exports provided: removePanel, duplicatePanel, copyPanel, editPanelJson, sharePanel, refreshPanel, toggleLegend, applyPanelTimeOverrides, getResolution, calculateInnerPanelHeight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePanel", function() { return removePanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "duplicatePanel", function() { return duplicatePanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyPanel", function() { return copyPanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "editPanelJson", function() { return editPanelJson; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sharePanel", function() { return sharePanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "refreshPanel", function() { return refreshPanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggleLegend", function() { return toggleLegend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyPanelTimeOverrides", function() { return applyPanelTimeOverrides; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getResolution", function() { return getResolution; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateInnerPanelHeight", function() { return calculateInnerPanelHeight; });
/* harmony import */ var app_core_store__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/store */ "./public/app/core/store.ts");
/* harmony import */ var app_features_dashboard_state_PanelModel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/features/dashboard/state/PanelModel */ "./public/app/features/dashboard/state/PanelModel.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/features/templating/template_srv */ "./public/app/features/templating/template_srv.ts");
/* harmony import */ var app_core_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/constants */ "./public/app/core/constants.ts");
// Store


// Utils





// Services

// Constants

var removePanel = function (dashboard, panel, ask) {
    // confirm deletion
    if (ask !== false) {
        var text2 = panel.alert ? 'Panel includes an alert rule, removing panel will also remove alert rule' : null;
        var confirmText = panel.alert ? 'YES' : null;
        app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('confirm-modal', {
            title: 'Remove Panel',
            text: 'Are you sure you want to remove this panel?',
            text2: text2,
            icon: 'fa-trash',
            confirmText: confirmText,
            yesText: 'Remove',
            onConfirm: function () { return removePanel(dashboard, panel, false); },
        });
        return;
    }
    dashboard.removePanel(panel);
};
var duplicatePanel = function (dashboard, panel) {
    dashboard.duplicatePanel(panel);
};
var copyPanel = function (panel) {
    app_core_store__WEBPACK_IMPORTED_MODULE_0__["default"].set(app_core_constants__WEBPACK_IMPORTED_MODULE_7__["LS_PANEL_COPY_KEY"], JSON.stringify(panel.getSaveModel()));
    app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('alert-success', ['Panel copied. Open Add Panel to paste']);
};
var replacePanel = function (dashboard, newPanel, oldPanel) {
    var index = dashboard.panels.findIndex(function (panel) {
        return panel.id === oldPanel.id;
    });
    var deletedPanel = dashboard.panels.splice(index, 1);
    dashboard.events.emit('panel-removed', deletedPanel);
    newPanel = new app_features_dashboard_state_PanelModel__WEBPACK_IMPORTED_MODULE_1__["PanelModel"](newPanel);
    newPanel.id = oldPanel.id;
    dashboard.panels.splice(index, 0, newPanel);
    dashboard.sortPanelsByGridPos();
    dashboard.events.emit('panel-added', newPanel);
};
var editPanelJson = function (dashboard, panel) {
    var model = {
        object: panel.getSaveModel(),
        updateHandler: function (newPanel, oldPanel) {
            replacePanel(dashboard, newPanel, oldPanel);
        },
        canUpdate: dashboard.meta.canEdit,
        enableCopy: true,
    };
    app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('show-modal', {
        src: 'public/app/partials/edit_json.html',
        model: model,
    });
};
var sharePanel = function (dashboard, panel) {
    app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('show-modal', {
        src: 'public/app/features/dashboard/components/ShareModal/template.html',
        model: {
            dashboard: dashboard,
            panel: panel,
        },
    });
};
var refreshPanel = function (panel) {
    panel.refresh();
};
var toggleLegend = function (panel) {
    console.log('Toggle legend is not implemented yet');
    // We need to set panel.legend defaults first
    // panel.legend.show = !panel.legend.show;
    refreshPanel(panel);
};
function applyPanelTimeOverrides(panel, timeRange) {
    var newTimeData = {
        timeInfo: '',
        timeRange: timeRange,
    };
    if (panel.timeFrom) {
        var timeFromInterpolated = app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_6__["default"].replace(panel.timeFrom, panel.scopedVars);
        var timeFromInfo = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["rangeUtil"].describeTextRange(timeFromInterpolated);
        if (timeFromInfo.invalid) {
            newTimeData.timeInfo = 'invalid time override';
            return newTimeData;
        }
        if (Object(lodash__WEBPACK_IMPORTED_MODULE_2__["isString"])(timeRange.raw.from)) {
            var timeFromDate = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(timeFromInfo.from);
            newTimeData.timeInfo = timeFromInfo.display;
            newTimeData.timeRange = {
                from: timeFromDate,
                to: _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parse(timeFromInfo.to),
                raw: {
                    from: timeFromInfo.from,
                    to: timeFromInfo.to,
                },
            };
        }
    }
    if (panel.timeShift) {
        var timeShiftInterpolated = app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_6__["default"].replace(panel.timeShift, panel.scopedVars);
        var timeShiftInfo = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["rangeUtil"].describeTextRange(timeShiftInterpolated);
        if (timeShiftInfo.invalid) {
            newTimeData.timeInfo = 'invalid timeshift';
            return newTimeData;
        }
        var timeShift = '-' + timeShiftInterpolated;
        newTimeData.timeInfo += ' timeshift ' + timeShift;
        var from = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parseDateMath(timeShift, newTimeData.timeRange.from, false);
        var to = _grafana_data__WEBPACK_IMPORTED_MODULE_3__["dateMath"].parseDateMath(timeShift, newTimeData.timeRange.to, true);
        newTimeData.timeRange = {
            from: from,
            to: to,
            raw: {
                from: from,
                to: to,
            },
        };
    }
    if (panel.hideTimeOverride) {
        newTimeData.timeInfo = '';
    }
    return newTimeData;
}
function getResolution(panel) {
    var htmlEl = document.getElementsByTagName('html')[0];
    var width = htmlEl.getBoundingClientRect().width; // https://stackoverflow.com/a/21454625
    return panel.maxDataPoints ? panel.maxDataPoints : Math.ceil(width * (panel.gridPos.w / 24));
}
function calculateInnerPanelHeight(panel, containerHeight) {
    return (containerHeight -
        (panel.hasTitle() ? app_core_config__WEBPACK_IMPORTED_MODULE_5__["default"].theme.panelHeaderHeight : 0) -
        app_core_config__WEBPACK_IMPORTED_MODULE_5__["default"].theme.panelPadding * 2 -
        app_core_constants__WEBPACK_IMPORTED_MODULE_7__["PANEL_BORDER"]);
}


/***/ }),

/***/ "./public/app/features/datasources/settings/HttpSettingsCtrl.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/datasources/settings/HttpSettingsCtrl.ts ***!
  \**********************************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var _utils_passwordHandlers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/passwordHandlers */ "./public/app/features/datasources/utils/passwordHandlers.ts");


app_core_core__WEBPACK_IMPORTED_MODULE_0__["coreModule"].directive('datasourceHttpSettings', function () {
    return {
        scope: {
            current: '=',
            suggestUrl: '@',
            noDirectAccess: '@',
        },
        templateUrl: 'public/app/features/datasources/partials/http_settings.html',
        link: {
            pre: function ($scope, elem, attrs) {
                // do not show access option if direct access is disabled
                $scope.showAccessOption = $scope.noDirectAccess !== 'true';
                $scope.showAccessHelp = false;
                $scope.toggleAccessHelp = function () {
                    $scope.showAccessHelp = !$scope.showAccessHelp;
                };
                $scope.getSuggestUrls = function () {
                    return [$scope.suggestUrl];
                };
                $scope.onBasicAuthPasswordReset = Object(_utils_passwordHandlers__WEBPACK_IMPORTED_MODULE_1__["createResetHandler"])($scope, _utils_passwordHandlers__WEBPACK_IMPORTED_MODULE_1__["PasswordFieldEnum"].BasicAuthPassword);
                $scope.onBasicAuthPasswordChange = Object(_utils_passwordHandlers__WEBPACK_IMPORTED_MODULE_1__["createChangeHandler"])($scope, _utils_passwordHandlers__WEBPACK_IMPORTED_MODULE_1__["PasswordFieldEnum"].BasicAuthPassword);
            },
        },
    };
});


/***/ }),

/***/ "./public/app/features/datasources/settings/TlsAuthSettingsCtrl.ts":
/*!*************************************************************************!*\
  !*** ./public/app/features/datasources/settings/TlsAuthSettingsCtrl.ts ***!
  \*************************************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");

app_core_core__WEBPACK_IMPORTED_MODULE_0__["coreModule"].directive('datasourceTlsAuthSettings', function () {
    return {
        scope: {
            current: '=',
        },
        templateUrl: 'public/app/features/datasources/partials/tls_auth_settings.html',
    };
});


/***/ }),

/***/ "./public/app/features/datasources/state/actions.ts":
/*!**********************************************************!*\
  !*** ./public/app/features/datasources/state/actions.ts ***!
  \**********************************************************/
/*! exports provided: dataSourceLoaded, dataSourcesLoaded, dataSourceMetaLoaded, dataSourceTypesLoad, dataSourceTypesLoaded, setDataSourcesSearchQuery, setDataSourcesLayoutMode, setDataSourceTypeSearchQuery, setDataSourceName, setIsDefault, loadDataSources, loadDataSource, addDataSource, loadDataSourceTypes, updateDataSource, deleteDataSource, nameExits, findNewName */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourceLoaded", function() { return dataSourceLoaded; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourcesLoaded", function() { return dataSourcesLoaded; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourceMetaLoaded", function() { return dataSourceMetaLoaded; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourceTypesLoad", function() { return dataSourceTypesLoad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourceTypesLoaded", function() { return dataSourceTypesLoaded; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDataSourcesSearchQuery", function() { return setDataSourcesSearchQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDataSourcesLayoutMode", function() { return setDataSourcesLayoutMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDataSourceTypeSearchQuery", function() { return setDataSourceTypeSearchQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDataSourceName", function() { return setDataSourceName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setIsDefault", function() { return setIsDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDataSources", function() { return loadDataSources; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDataSource", function() { return loadDataSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addDataSource", function() { return addDataSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDataSourceTypes", function() { return loadDataSourceTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateDataSource", function() { return updateDataSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteDataSource", function() { return deleteDataSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nameExits", function() { return nameExits; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNewName", function() { return findNewName; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/plugins/datasource_srv */ "./public/app/features/plugins/datasource_srv.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./navModel */ "./public/app/features/datasources/state/navModel.ts");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/redux/actionCreatorFactory */ "./public/app/core/redux/actionCreatorFactory.ts");
/* harmony import */ var app_features_plugins_PluginSettingsCache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/features/plugins/PluginSettingsCache */ "./public/app/features/plugins/PluginSettingsCache.ts");
/* harmony import */ var app_features_plugins_plugin_loader__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/features/plugins/plugin_loader */ "./public/app/features/plugins/plugin_loader.ts");










var dataSourceLoaded = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('LOAD_DATA_SOURCE').create();
var dataSourcesLoaded = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('LOAD_DATA_SOURCES').create();
var dataSourceMetaLoaded = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('LOAD_DATA_SOURCE_META').create();
var dataSourceTypesLoad = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_7__["noPayloadActionCreatorFactory"])('LOAD_DATA_SOURCE_TYPES').create();
var dataSourceTypesLoaded = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('LOADED_DATA_SOURCE_TYPES').create();
var setDataSourcesSearchQuery = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('SET_DATA_SOURCES_SEARCH_QUERY').create();
var setDataSourcesLayoutMode = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('SET_DATA_SOURCES_LAYOUT_MODE').create();
var setDataSourceTypeSearchQuery = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('SET_DATA_SOURCE_TYPE_SEARCH_QUERY').create();
var setDataSourceName = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('SET_DATA_SOURCE_NAME').create();
var setIsDefault = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["actionCreatorFactory"])('SET_IS_DEFAULT').create();
function loadDataSources() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().get('/api/datasources')];
                case 1:
                    response = _a.sent();
                    dispatch(dataSourcesLoaded(response));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadDataSource(id) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dataSource, pluginInfo, plugin;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().get("/api/datasources/" + id)];
                case 1:
                    dataSource = _a.sent();
                    return [4 /*yield*/, Object(app_features_plugins_PluginSettingsCache__WEBPACK_IMPORTED_MODULE_8__["getPluginSettings"])(dataSource.type)];
                case 2:
                    pluginInfo = (_a.sent());
                    return [4 /*yield*/, Object(app_features_plugins_plugin_loader__WEBPACK_IMPORTED_MODULE_9__["importDataSourcePlugin"])(pluginInfo)];
                case 3:
                    plugin = _a.sent();
                    dispatch(dataSourceLoaded(dataSource));
                    dispatch(dataSourceMetaLoaded(pluginInfo));
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_4__["updateNavIndex"])(Object(_navModel__WEBPACK_IMPORTED_MODULE_5__["buildNavModel"])(dataSource, plugin)));
                    return [2 /*return*/];
            }
        });
    }); };
}
function addDataSource(plugin) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dataSources, newInstance, result;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, dispatch(loadDataSources())];
                case 1:
                    _a.sent();
                    dataSources = getStore().dataSources.dataSources;
                    newInstance = {
                        name: plugin.name,
                        type: plugin.id,
                        access: 'proxy',
                        isDefault: dataSources.length === 0,
                    };
                    if (nameExits(dataSources, newInstance.name)) {
                        newInstance.name = findNewName(dataSources, newInstance.name);
                    }
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().post('/api/datasources', newInstance)];
                case 2:
                    result = _a.sent();
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_4__["updateLocation"])({ path: "/datasources/edit/" + result.id }));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadDataSourceTypes() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var result;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    dispatch(dataSourceTypesLoad());
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().get('/api/plugins', { enabled: 1, type: 'datasource' })];
                case 1:
                    result = _a.sent();
                    dispatch(dataSourceTypesLoaded(result));
                    return [2 /*return*/];
            }
        });
    }); };
}
function updateDataSource(dataSource) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().put("/api/datasources/" + dataSource.id, dataSource)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, updateFrontendSettings()];
                case 2:
                    _a.sent();
                    return [2 /*return*/, dispatch(loadDataSource(dataSource.id))];
            }
        });
    }); };
}
function deleteDataSource() {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dataSource;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    dataSource = getStore().dataSources.dataSource;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])().delete("/api/datasources/" + dataSource.id)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, updateFrontendSettings()];
                case 2:
                    _a.sent();
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_4__["updateLocation"])({ path: '/datasources' }));
                    return [2 /*return*/];
            }
        });
    }); };
}
function nameExits(dataSources, name) {
    return (dataSources.filter(function (dataSource) {
        return dataSource.name.toLowerCase() === name.toLowerCase();
    }).length > 0);
}
function findNewName(dataSources, name) {
    // Need to loop through current data sources to make sure
    // the name doesn't exist
    while (nameExits(dataSources, name)) {
        // If there's a duplicate name that doesn't end with '-x'
        // we can add -1 to the name and be done.
        if (!nameHasSuffix(name)) {
            name = name + "-1";
        }
        else {
            // if there's a duplicate name that ends with '-x'
            // we can try to increment the last digit until the name is unique
            // remove the 'x' part and replace it with the new number
            name = "" + getNewName(name) + incrementLastDigit(getLastDigit(name));
        }
    }
    return name;
}
function updateFrontendSettings() {
    return Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_2__["getBackendSrv"])()
        .get('/api/frontend/settings')
        .then(function (settings) {
        _core_config__WEBPACK_IMPORTED_MODULE_1__["default"].datasources = settings.datasources;
        _core_config__WEBPACK_IMPORTED_MODULE_1__["default"].defaultDatasource = settings.defaultDatasource;
        Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_3__["getDatasourceSrv"])().init();
    });
}
function nameHasSuffix(name) {
    return name.endsWith('-', name.length - 1);
}
function getLastDigit(name) {
    return parseInt(name.slice(-1), 10);
}
function incrementLastDigit(digit) {
    return isNaN(digit) ? 1 : digit + 1;
}
function getNewName(name) {
    return name.slice(0, name.length - 1);
}


/***/ }),

/***/ "./public/app/features/datasources/state/navModel.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/datasources/state/navModel.ts ***!
  \***********************************************************/
/*! exports provided: buildNavModel, getDataSourceLoadingNav */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildNavModel", function() { return buildNavModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataSourceLoadingNav", function() { return getDataSourceLoadingNav; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



function buildNavModel(dataSource, plugin) {
    var e_1, _a;
    var pluginMeta = plugin.meta;
    var navModel = {
        img: pluginMeta.info.logos.large,
        id: 'datasource-' + dataSource.id,
        subTitle: "Type: " + pluginMeta.name,
        url: '',
        text: dataSource.name,
        breadcrumbs: [{ title: 'Data Sources', url: 'datasources' }],
        children: [
            {
                active: false,
                icon: 'fa fa-fw fa-sliders',
                id: "datasource-settings-" + dataSource.id,
                text: 'Settings',
                url: "datasources/edit/" + dataSource.id + "/",
            },
        ],
    };
    if (plugin.configPages) {
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](plugin.configPages), _c = _b.next(); !_c.done; _c = _b.next()) {
                var page = _c.value;
                navModel.children.push({
                    active: false,
                    text: page.title,
                    icon: page.icon,
                    url: "datasources/edit/" + dataSource.id + "/?page=" + page.id,
                    id: "datasource-page-" + page.id,
                });
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    if (pluginMeta.includes && hasDashboards(pluginMeta.includes)) {
        navModel.children.push({
            active: false,
            icon: 'fa fa-fw fa-th-large',
            id: "datasource-dashboards-" + dataSource.id,
            text: 'Dashboards',
            url: "datasources/edit/" + dataSource.id + "/dashboards",
        });
    }
    if (app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].buildInfo.isEnterprise) {
        navModel.children.push({
            active: false,
            icon: 'fa fa-fw fa-lock',
            id: "datasource-permissions-" + dataSource.id,
            text: 'Permissions',
            url: "datasources/edit/" + dataSource.id + "/permissions",
        });
    }
    return navModel;
}
function getDataSourceLoadingNav(pageName) {
    var e_2, _a;
    var main = buildNavModel({
        access: '',
        basicAuth: false,
        basicAuthUser: '',
        basicAuthPassword: '',
        withCredentials: false,
        database: '',
        id: 1,
        isDefault: false,
        jsonData: { authType: 'credentials', defaultRegion: 'eu-west-2' },
        name: 'Loading',
        orgId: 1,
        password: '',
        readOnly: false,
        type: 'Loading',
        typeLogoUrl: 'public/img/icn-datasource.svg',
        url: '',
        user: '',
    }, {
        meta: {
            id: '1',
            type: _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["PluginType"].datasource,
            name: '',
            info: {
                author: {
                    name: '',
                    url: '',
                },
                description: '',
                links: [{ name: '', url: '' }],
                logos: {
                    large: '',
                    small: '',
                },
                screenshots: [],
                updated: '',
                version: '',
            },
            includes: [],
            module: '',
            baseUrl: '',
        },
    });
    var node;
    try {
        // find active page
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](main.children), _c = _b.next(); !_c.done; _c = _b.next()) {
            var child = _c.value;
            if (child.id.indexOf(pageName) > 0) {
                child.active = true;
                node = child;
                break;
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return {
        main: main,
        node: node,
    };
}
function hasDashboards(includes) {
    return (includes.find(function (include) {
        return include.type === 'dashboard';
    }) !== undefined);
}


/***/ }),

/***/ "./public/app/features/datasources/state/reducers.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/datasources/state/reducers.ts ***!
  \***********************************************************/
/*! exports provided: initialState, dataSourcesReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourcesReducer", function() { return dataSourcesReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/datasources/state/actions.ts");
/* harmony import */ var app_core_components_LayoutSelector_LayoutSelector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/components/LayoutSelector/LayoutSelector */ "./public/app/core/components/LayoutSelector/LayoutSelector.tsx");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");




var initialState = {
    dataSources: [],
    dataSource: {},
    layoutMode: app_core_components_LayoutSelector_LayoutSelector__WEBPACK_IMPORTED_MODULE_2__["LayoutModes"].List,
    searchQuery: '',
    dataSourcesCount: 0,
    dataSourceTypes: [],
    dataSourceTypeSearchQuery: '',
    hasFetched: false,
    isLoadingDataSources: false,
    dataSourceMeta: {},
};
var dataSourcesReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_3__["reducerFactory"])(initialState)
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["dataSourcesLoaded"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hasFetched: true, dataSources: action.payload, dataSourcesCount: action.payload.length })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["dataSourceLoaded"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSource: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["setDataSourcesSearchQuery"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchQuery: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["setDataSourcesLayoutMode"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { layoutMode: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["dataSourceTypesLoad"],
    mapper: function (state) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSourceTypes: [], isLoadingDataSources: true })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["dataSourceTypesLoaded"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSourceTypes: action.payload, isLoadingDataSources: false })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["setDataSourceTypeSearchQuery"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSourceTypeSearchQuery: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["dataSourceMetaLoaded"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSourceMeta: action.payload })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["setDataSourceName"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSource: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.dataSource, { name: action.payload }) })); },
})
    .addMapper({
    filter: _actions__WEBPACK_IMPORTED_MODULE_1__["setIsDefault"],
    mapper: function (state, action) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dataSource: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.dataSource, { isDefault: action.payload }) })); },
})
    .create();
/* harmony default export */ __webpack_exports__["default"] = ({
    dataSources: dataSourcesReducer,
});


/***/ }),

/***/ "./public/app/features/datasources/utils/passwordHandlers.ts":
/*!*******************************************************************!*\
  !*** ./public/app/features/datasources/utils/passwordHandlers.ts ***!
  \*******************************************************************/
/*! exports provided: PasswordFieldEnum, createResetHandler, createChangeHandler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PasswordFieldEnum", function() { return PasswordFieldEnum; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createResetHandler", function() { return createResetHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createChangeHandler", function() { return createChangeHandler; });
/**
 * Set of handlers for secure password field in Angular components. They handle backward compatibility with
 * passwords stored in plain text fields.
 */
var PasswordFieldEnum;
(function (PasswordFieldEnum) {
    PasswordFieldEnum["Password"] = "password";
    PasswordFieldEnum["BasicAuthPassword"] = "basicAuthPassword";
})(PasswordFieldEnum || (PasswordFieldEnum = {}));
var createResetHandler = function (ctrl, field) { return function (event) {
    event.preventDefault();
    // Reset also normal plain text password to remove it and only save it in secureJsonData.
    ctrl.current[field] = null;
    ctrl.current.secureJsonFields[field] = false;
    ctrl.current.secureJsonData = ctrl.current.secureJsonData || {};
    ctrl.current.secureJsonData[field] = '';
}; };
var createChangeHandler = function (ctrl, field) { return function (event) {
    ctrl.current.secureJsonData = ctrl.current.secureJsonData || {};
    ctrl.current.secureJsonData[field] = event.currentTarget.value;
}; };


/***/ }),

/***/ "./public/app/features/explore/QueryField.tsx":
/*!****************************************************!*\
  !*** ./public/app/features/explore/QueryField.tsx ***!
  \****************************************************/
/*! exports provided: QueryField, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryField", function() { return QueryField; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_slate_react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/slate-react */ "./node_modules/@grafana/slate-react/lib/slate-react.es.js");
/* harmony import */ var slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! slate-plain-serializer */ "./node_modules/slate-plain-serializer/lib/slate-plain-serializer.es.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _slate_plugins_clear__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./slate-plugins/clear */ "./public/app/features/explore/slate-plugins/clear.ts");
/* harmony import */ var _slate_plugins_newline__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./slate-plugins/newline */ "./public/app/features/explore/slate-plugins/newline.ts");
/* harmony import */ var _slate_plugins_selection_shortcuts__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./slate-plugins/selection_shortcuts */ "./public/app/features/explore/slate-plugins/selection_shortcuts.ts");
/* harmony import */ var _slate_plugins_indentation__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./slate-plugins/indentation */ "./public/app/features/explore/slate-plugins/indentation.ts");
/* harmony import */ var _slate_plugins_clipboard__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./slate-plugins/clipboard */ "./public/app/features/explore/slate-plugins/clipboard.ts");
/* harmony import */ var _slate_plugins_runner__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./slate-plugins/runner */ "./public/app/features/explore/slate-plugins/runner.ts");
/* harmony import */ var _slate_plugins_suggestions__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./slate-plugins/suggestions */ "./public/app/features/explore/slate-plugins/suggestions.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");














/**
 * Renders an editor field.
 * Pass initial value as initialQuery and listen to changes in props.onValueChanged.
 * This component can only process strings. Internally it uses Slate Value.
 * Implement props.onTypeahead to use suggestions, see PromQueryField.tsx as an example.
 */
var QueryField = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueryField, _super);
    function QueryField(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.lastExecutedValue = null;
        /**
         * Update local state, propagate change upstream and optionally run the query afterwards.
         */
        _this.onChange = function (value, runQuery) {
            var documentChanged = value.document !== _this.state.value.document;
            var prevValue = _this.state.value;
            // Update local state with new value and optionally change value upstream.
            _this.setState({ value: value }, function () {
                // The diff is needed because the actual value of editor have much more metadata (for example text selection)
                // that is not passed upstream so every change of editor value does not mean change of the query text.
                if (documentChanged) {
                    var textChanged = slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__["default"].serialize(prevValue) !== slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__["default"].serialize(value);
                    if (textChanged && runQuery) {
                        _this.runOnChangeAndRunQuery();
                    }
                    if (textChanged && !runQuery) {
                        // Debounce change propagation by default for perf reasons.
                        _this.runOnChangeDebounced();
                    }
                }
            });
        };
        _this.runOnChange = function () {
            var onChange = _this.props.onChange;
            if (onChange) {
                onChange(slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__["default"].serialize(_this.state.value));
            }
        };
        _this.runOnRunQuery = function () {
            var onRunQuery = _this.props.onRunQuery;
            if (onRunQuery) {
                onRunQuery();
                _this.lastExecutedValue = _this.state.value;
            }
        };
        _this.runOnChangeAndRunQuery = function () {
            // onRunQuery executes query from Redux in Explore so it needs to be updated sync in case we want to run
            // the query.
            _this.runOnChange();
            _this.runOnRunQuery();
        };
        /**
         * We need to handle blur events here mainly because of dashboard panels which expect to have query executed on blur.
         */
        _this.handleBlur = function (event, editor, next) {
            var previousValue = _this.lastExecutedValue ? slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__["default"].serialize(_this.lastExecutedValue) : null;
            var currentValue = slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__["default"].serialize(editor.value);
            if (previousValue !== currentValue) {
                _this.runOnChangeAndRunQuery();
            }
            return next();
        };
        _this.runOnChangeDebounced = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.debounce(_this.runOnChange, 500);
        var onTypeahead = props.onTypeahead, cleanText = props.cleanText, portalOrigin = props.portalOrigin, onWillApplySuggestion = props.onWillApplySuggestion;
        // Base plugins
        _this.plugins = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([
            Object(_slate_plugins_newline__WEBPACK_IMPORTED_MODULE_7__["default"])(),
            Object(_slate_plugins_suggestions__WEBPACK_IMPORTED_MODULE_12__["default"])({ onTypeahead: onTypeahead, cleanText: cleanText, portalOrigin: portalOrigin, onWillApplySuggestion: onWillApplySuggestion, component: _this }),
            Object(_slate_plugins_clear__WEBPACK_IMPORTED_MODULE_6__["default"])(),
            Object(_slate_plugins_runner__WEBPACK_IMPORTED_MODULE_11__["default"])({ handler: _this.runOnChangeAndRunQuery }),
            Object(_slate_plugins_selection_shortcuts__WEBPACK_IMPORTED_MODULE_8__["default"])(),
            Object(_slate_plugins_indentation__WEBPACK_IMPORTED_MODULE_9__["default"])(),
            Object(_slate_plugins_clipboard__WEBPACK_IMPORTED_MODULE_10__["default"])()
        ], (props.additionalPlugins || [])).filter(function (p) { return p; });
        _this.state = {
            suggestions: [],
            typeaheadContext: null,
            typeaheadPrefix: '',
            typeaheadText: '',
            value: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_13__["makeValue"])(props.query || '', props.syntax),
        };
        return _this;
    }
    QueryField.prototype.componentDidMount = function () {
        this.mounted = true;
    };
    QueryField.prototype.componentWillUnmount = function () {
        this.mounted = false;
        clearTimeout(this.resetTimer);
    };
    QueryField.prototype.componentDidUpdate = function (prevProps, prevState) {
        var _a = this.props, query = _a.query, syntax = _a.syntax;
        var value = this.state.value;
        // Handle two way binging between local state and outside prop.
        // if query changed from the outside
        if (query !== prevProps.query) {
            // and we have a version that differs
            if (query !== slate_plain_serializer__WEBPACK_IMPORTED_MODULE_4__["default"].serialize(value)) {
                this.setState({ value: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_13__["makeValue"])(query || '', syntax) });
            }
        }
    };
    QueryField.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        if (nextProps.syntaxLoaded && !this.props.syntaxLoaded) {
            // Need a bogus edit to re-render the editor after syntax has fully loaded
            var editor = this.editor.insertText(' ').deleteBackward(1);
            this.onChange(editor.value, true);
        }
    };
    QueryField.prototype.render = function () {
        var _this = this;
        var disabled = this.props.disabled;
        var wrapperClassName = classnames__WEBPACK_IMPORTED_MODULE_5___default()('slate-query-field__wrapper', {
            'slate-query-field__wrapper--disabled': disabled,
        });
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: wrapperClassName },
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "slate-query-field" },
                react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_grafana_slate_react__WEBPACK_IMPORTED_MODULE_3__["Editor"], { ref: function (editor) { return (_this.editor = editor); }, schema: _grafana_ui__WEBPACK_IMPORTED_MODULE_13__["SCHEMA"], autoCorrect: false, readOnly: this.props.disabled, onBlur: this.handleBlur, 
                    // onKeyDown={this.onKeyDown}
                    onChange: function (change) {
                        _this.onChange(change.value, false);
                    }, placeholder: this.props.placeholder, plugins: this.plugins, spellCheck: false, value: this.state.value }))));
    };
    return QueryField;
}(react__WEBPACK_IMPORTED_MODULE_2___default.a.PureComponent));

/* harmony default export */ __webpack_exports__["default"] = (QueryField);


/***/ }),

/***/ "./public/app/features/explore/Typeahead.tsx":
/*!***************************************************!*\
  !*** ./public/app/features/explore/Typeahead.tsx ***!
  \***************************************************/
/*! exports provided: Typeahead, TypeaheadWithTheme */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Typeahead", function() { return Typeahead; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TypeaheadWithTheme", function() { return TypeaheadWithTheme; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var react_window__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-window */ "./node_modules/react-window/dist/index.esm.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_types_explore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/types/explore */ "./public/app/types/explore.ts");
/* harmony import */ var _TypeaheadItem__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./TypeaheadItem */ "./public/app/features/explore/TypeaheadItem.tsx");
/* harmony import */ var _TypeaheadInfo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./TypeaheadInfo */ "./public/app/features/explore/TypeaheadInfo.tsx");
/* harmony import */ var _utils_typeahead__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/typeahead */ "./public/app/features/explore/utils/typeahead.ts");










var modulo = function (a, n) { return a - n * Math.floor(a / n); };
var Typeahead = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Typeahead, _super);
    function Typeahead(props) {
        var _this = _super.call(this, props) || this;
        _this.listRef = Object(react__WEBPACK_IMPORTED_MODULE_1__["createRef"])();
        _this.componentDidMount = function () {
            _this.props.menuRef(_this);
            document.addEventListener('selectionchange', _this.handleSelectionChange);
        };
        _this.componentWillUnmount = function () {
            document.removeEventListener('selectionchange', _this.handleSelectionChange);
        };
        _this.handleSelectionChange = function () {
            _this.forceUpdate();
        };
        _this.componentDidUpdate = function (prevProps, prevState) {
            if (prevState.typeaheadIndex !== _this.state.typeaheadIndex && _this.listRef && _this.listRef.current) {
                if (_this.state.typeaheadIndex === 1) {
                    _this.listRef.current.scrollToItem(0); // special case for handling the first group label
                    return;
                }
                _this.listRef.current.scrollToItem(_this.state.typeaheadIndex);
            }
            if (lodash__WEBPACK_IMPORTED_MODULE_3___default.a.isEqual(prevProps.groupedItems, _this.props.groupedItems) === false) {
                var allItems = Object(_utils_typeahead__WEBPACK_IMPORTED_MODULE_9__["flattenGroupItems"])(_this.props.groupedItems);
                var longestLabel = Object(_utils_typeahead__WEBPACK_IMPORTED_MODULE_9__["calculateLongestLabel"])(allItems);
                var _a = Object(_utils_typeahead__WEBPACK_IMPORTED_MODULE_9__["calculateListSizes"])(_this.props.theme, allItems, longestLabel), listWidth = _a.listWidth, listHeight = _a.listHeight, itemHeight = _a.itemHeight;
                _this.setState({ listWidth: listWidth, listHeight: listHeight, itemHeight: itemHeight, allItems: allItems });
            }
        };
        _this.onMouseEnter = function (index) {
            _this.setState({
                hoveredItem: index,
            });
        };
        _this.onMouseLeave = function () {
            _this.setState({
                hoveredItem: null,
            });
        };
        _this.moveMenuIndex = function (moveAmount) {
            var itemCount = _this.state.allItems.length;
            if (itemCount) {
                // Select next suggestion
                event.preventDefault();
                var newTypeaheadIndex = modulo(_this.state.typeaheadIndex + moveAmount, itemCount);
                if (_this.state.allItems[newTypeaheadIndex].kind === app_types_explore__WEBPACK_IMPORTED_MODULE_6__["CompletionItemKind"].GroupTitle) {
                    newTypeaheadIndex = modulo(newTypeaheadIndex + moveAmount, itemCount);
                }
                _this.setState({
                    typeaheadIndex: newTypeaheadIndex,
                });
                return;
            }
        };
        _this.insertSuggestion = function () {
            _this.props.onSelectSuggestion(_this.state.allItems[_this.state.typeaheadIndex]);
        };
        var allItems = Object(_utils_typeahead__WEBPACK_IMPORTED_MODULE_9__["flattenGroupItems"])(props.groupedItems);
        var longestLabel = Object(_utils_typeahead__WEBPACK_IMPORTED_MODULE_9__["calculateLongestLabel"])(allItems);
        var _a = Object(_utils_typeahead__WEBPACK_IMPORTED_MODULE_9__["calculateListSizes"])(props.theme, allItems, longestLabel), listWidth = _a.listWidth, listHeight = _a.listHeight, itemHeight = _a.itemHeight;
        _this.state = { listWidth: listWidth, listHeight: listHeight, itemHeight: itemHeight, hoveredItem: null, typeaheadIndex: 1, allItems: allItems };
        return _this;
    }
    Object.defineProperty(Typeahead.prototype, "menuPosition", {
        get: function () {
            // Exit for unit tests
            if (!window.getSelection) {
                return '';
            }
            var selection = window.getSelection();
            var node = selection.anchorNode;
            // Align menu overlay to editor node
            if (node) {
                // Read from DOM
                var rect = node.parentElement.getBoundingClientRect();
                var scrollX = window.scrollX;
                var scrollY = window.scrollY;
                return "position: absolute; display: flex; top: " + (rect.top + scrollY + rect.height + 6) + "px; left: " + (rect.left +
                    scrollX -
                    2) + "px";
            }
            return '';
        },
        enumerable: true,
        configurable: true
    });
    Typeahead.prototype.render = function () {
        var _this = this;
        var _a = this.props, prefix = _a.prefix, theme = _a.theme, isOpen = _a.isOpen, origin = _a.origin;
        var _b = this.state, allItems = _b.allItems, listWidth = _b.listWidth, listHeight = _b.listHeight, itemHeight = _b.itemHeight, hoveredItem = _b.hoveredItem, typeaheadIndex = _b.typeaheadIndex;
        var showDocumentation = hoveredItem || typeaheadIndex;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Portal, { origin: origin, isOpen: isOpen, style: this.menuPosition },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", { className: "typeahead" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_window__WEBPACK_IMPORTED_MODULE_4__["FixedSizeList"], { ref: this.listRef, itemCount: allItems.length, itemSize: itemHeight, itemKey: function (index) {
                        var item = allItems && allItems[index];
                        var key = item ? index + "-" + item.label : "" + index;
                        return key;
                    }, width: listWidth, height: listHeight }, function (_a) {
                    var index = _a.index, style = _a.style;
                    var item = allItems && allItems[index];
                    if (!item) {
                        return null;
                    }
                    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TypeaheadItem__WEBPACK_IMPORTED_MODULE_7__["TypeaheadItem"], { onClickItem: function () { return _this.props.onSelectSuggestion(item); }, isSelected: allItems[typeaheadIndex] === item, item: item, prefix: prefix, style: style, onMouseEnter: function () { return _this.onMouseEnter(index); }, onMouseLeave: _this.onMouseLeave }));
                })),
            showDocumentation && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_TypeaheadInfo__WEBPACK_IMPORTED_MODULE_8__["TypeaheadInfo"], { width: listWidth, height: listHeight, theme: theme, item: allItems[hoveredItem ? hoveredItem : typeaheadIndex] }))));
    };
    return Typeahead;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));

var TypeaheadWithTheme = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_5__["withTheme"])(Typeahead);
var Portal = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Portal, _super);
    function Portal(props) {
        var _this = _super.call(this, props) || this;
        var _a = props.index, index = _a === void 0 ? 0 : _a, _b = props.origin, origin = _b === void 0 ? 'query' : _b, style = props.style;
        _this.node = document.createElement('div');
        _this.node.setAttribute('style', style);
        _this.node.classList.add("slate-typeahead", "slate-typeahead-" + origin + "-" + index);
        document.body.appendChild(_this.node);
        return _this;
    }
    Portal.prototype.componentWillUnmount = function () {
        document.body.removeChild(this.node);
    };
    Portal.prototype.render = function () {
        if (this.props.isOpen) {
            this.node.setAttribute('style', this.props.style);
            this.node.classList.add("slate-typeahead--open");
            return react_dom__WEBPACK_IMPORTED_MODULE_2___default.a.createPortal(this.props.children, this.node);
        }
        else {
            this.node.classList.remove("slate-typeahead--open");
        }
        return null;
    };
    return Portal;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));


/***/ }),

/***/ "./public/app/features/explore/TypeaheadInfo.tsx":
/*!*******************************************************!*\
  !*** ./public/app/features/explore/TypeaheadInfo.tsx ***!
  \*******************************************************/
/*! exports provided: TypeaheadInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TypeaheadInfo", function() { return TypeaheadInfo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var TypeaheadInfo = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TypeaheadInfo, _super);
    function TypeaheadInfo(props) {
        var _this = _super.call(this, props) || this;
        _this.getStyles = function (visible) {
            var _a = _this.props, height = _a.height, theme = _a.theme;
            return {
                typeaheadItem: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n        label: type-ahead-item;\n        padding: ", " ", " ", " ", ";\n        border-radius: ", ";\n        border: ", ";\n        overflow-y: scroll;\n        overflow-x: hidden;\n        outline: none;\n        background: ", ";\n        color: ", ";\n        box-shadow: ", ";\n        visibility: ", ";\n        width: 250px;\n        height: ", "px;\n        position: relative;\n      "], ["\n        label: type-ahead-item;\n        padding: ", " ", " ", " ", ";\n        border-radius: ", ";\n        border: ",
                    ";\n        overflow-y: scroll;\n        overflow-x: hidden;\n        outline: none;\n        background: ", ";\n        color: ", ";\n        box-shadow: ",
                    ";\n        visibility: ", ";\n        width: 250px;\n        height: ", "px;\n        position: relative;\n      "])), theme.spacing.sm, theme.spacing.sm, theme.spacing.sm, theme.spacing.md, theme.border.radius.md, Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["selectThemeVariant"])({ light: "solid 1px " + theme.colors.gray5, dark: "solid 1px " + theme.colors.dark1 }, theme.type), Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["selectThemeVariant"])({ light: theme.colors.white, dark: theme.colors.dark4 }, theme.type), theme.colors.text, Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["selectThemeVariant"])({ light: "0 5px 10px 0 " + theme.colors.gray5, dark: "0 5px 10px 0 " + theme.colors.black }, theme.type), visible === true ? 'visible' : 'hidden', height + parseInt(theme.spacing.xxs, 10)),
            };
        };
        return _this;
    }
    TypeaheadInfo.prototype.render = function () {
        var item = this.props.item;
        var visible = item && !!item.documentation;
        var label = item ? item.label : '';
        var documentation = item && item.documentation ? item.documentation : '';
        var styles = this.getStyles(visible);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_2__["cx"])([styles.typeaheadItem]) },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("b", null, label),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("hr", null),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, documentation)));
    };
    return TypeaheadInfo;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var templateObject_1;


/***/ }),

/***/ "./public/app/features/explore/TypeaheadItem.tsx":
/*!*******************************************************!*\
  !*** ./public/app/features/explore/TypeaheadItem.tsx ***!
  \*******************************************************/
/*! exports provided: TypeaheadItem */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TypeaheadItem", function() { return TypeaheadItem; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_highlight_words__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-highlight-words */ "./node_modules/react-highlight-words/dist/main.js");
/* harmony import */ var react_highlight_words__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_highlight_words__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_types_explore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/types/explore */ "./public/app/types/explore.ts");


// @ts-ignore




var getStyles = function (theme) { return ({
    typeaheadItem: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: type-ahead-item;\n    height: auto;\n    font-family: ", ";\n    padding: ", " ", " ", " ", ";\n    font-size: ", ";\n    text-overflow: ellipsis;\n    overflow: hidden;\n    z-index: 1;\n    display: block;\n    white-space: nowrap;\n    cursor: pointer;\n    transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), border-color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1),\n      background 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), padding 0.15s cubic-bezier(0.645, 0.045, 0.355, 1);\n  "], ["\n    label: type-ahead-item;\n    height: auto;\n    font-family: ", ";\n    padding: ", " ", " ", " ", ";\n    font-size: ", ";\n    text-overflow: ellipsis;\n    overflow: hidden;\n    z-index: 1;\n    display: block;\n    white-space: nowrap;\n    cursor: pointer;\n    transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), border-color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1),\n      background 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), padding 0.15s cubic-bezier(0.645, 0.045, 0.355, 1);\n  "])), theme.typography.fontFamily.monospace, theme.spacing.sm, theme.spacing.sm, theme.spacing.sm, theme.spacing.md, theme.typography.size.sm),
    typeaheadItemSelected: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: type-ahead-item-selected;\n    background-color: ", ";\n  "], ["\n    label: type-ahead-item-selected;\n    background-color: ", ";\n  "])), Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["selectThemeVariant"])({ light: theme.colors.gray6, dark: theme.colors.dark9 }, theme.type)),
    typeaheadItemMatch: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_3 || (templateObject_3 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: type-ahead-item-match;\n    color: ", ";\n    border-bottom: 1px solid ", ";\n    padding: inherit;\n    background: inherit;\n  "], ["\n    label: type-ahead-item-match;\n    color: ", ";\n    border-bottom: 1px solid ", ";\n    padding: inherit;\n    background: inherit;\n  "])), theme.colors.yellow, theme.colors.yellow),
    typeaheadItemGroupTitle: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_4 || (templateObject_4 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n    label: type-ahead-item-group-title;\n    color: ", ";\n    font-size: ", ";\n    line-height: ", ";\n    padding: ", ";\n  "], ["\n    label: type-ahead-item-group-title;\n    color: ", ";\n    font-size: ", ";\n    line-height: ", ";\n    padding: ", ";\n  "])), theme.colors.textWeak, theme.typography.size.sm, theme.typography.lineHeight.lg, theme.spacing.sm),
}); };
var TypeaheadItem = function (props) {
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["ThemeContext"]);
    var styles = getStyles(theme);
    var isSelected = props.isSelected, item = props.item, prefix = props.prefix, style = props.style, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, onClickItem = props.onClickItem;
    var className = isSelected ? Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])([styles.typeaheadItem, styles.typeaheadItemSelected]) : Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])([styles.typeaheadItem]);
    var highlightClassName = Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])([styles.typeaheadItemMatch]);
    var itemGroupTitleClassName = Object(emotion__WEBPACK_IMPORTED_MODULE_3__["cx"])([styles.typeaheadItemGroupTitle]);
    var label = item.label || '';
    if (item.kind === app_types_explore__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].GroupTitle) {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: itemGroupTitleClassName, style: style },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, label)));
    }
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", { className: className, style: style, onMouseDown: onClickItem, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_highlight_words__WEBPACK_IMPORTED_MODULE_2___default.a, { textToHighlight: label, searchWords: [prefix], highlightClassName: highlightClassName })));
};
var templateObject_1, templateObject_2, templateObject_3, templateObject_4;


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/braces.ts":
/*!*************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/braces.ts ***!
  \*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BracesPlugin; });
var BRACES = {
    '[': ']',
    '{': '}',
    '(': ')',
};
function BracesPlugin() {
    return {
        onKeyDown: function (event, editor, next) {
            var value = editor.value;
            switch (event.key) {
                case '(':
                case '{':
                case '[': {
                    event.preventDefault();
                    var _a = value.selection, _b = _a.start, startOffset = _b.offset, startKey = _b.key, _c = _a.end, endOffset = _c.offset, endKey = _c.key, focusOffset = _a.focus.offset;
                    var text = value.focusText.text;
                    // If text is selected, wrap selected text in parens
                    if (value.selection.isExpanded) {
                        editor
                            .insertTextByKey(startKey, startOffset, event.key)
                            .insertTextByKey(endKey, endOffset + 1, BRACES[event.key])
                            .moveEndBackward(1);
                    }
                    else if (focusOffset === text.length ||
                        text[focusOffset] === ' ' ||
                        Object.values(BRACES).includes(text[focusOffset])) {
                        editor.insertText("" + event.key + BRACES[event.key]).moveBackward(1);
                    }
                    else {
                        editor.insertText(event.key);
                    }
                    return true;
                }
                case 'Backspace': {
                    var text = value.anchorText.text;
                    var offset = value.selection.anchor.offset;
                    var previousChar = text[offset - 1];
                    var nextChar = text[offset];
                    if (BRACES[previousChar] && BRACES[previousChar] === nextChar) {
                        event.preventDefault();
                        // Remove closing brace if directly following
                        editor
                            .deleteBackward(1)
                            .deleteForward(1)
                            .focus();
                        return true;
                    }
                }
                default: {
                    break;
                }
            }
            return next();
        },
    };
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/clear.ts":
/*!************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/clear.ts ***!
  \************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ClearPlugin; });
// Clears the rest of the line after the caret
function ClearPlugin() {
    return {
        onKeyDown: function (event, editor, next) {
            var value = editor.value;
            if (value.selection.isExpanded) {
                return next();
            }
            if (event.key === 'k' && event.ctrlKey) {
                event.preventDefault();
                var text = value.anchorText.text;
                var offset = value.selection.anchor.offset;
                var length = text.length;
                var forward = length - offset;
                editor.deleteForward(forward);
                return true;
            }
            return next();
        },
    };
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/clipboard.ts":
/*!****************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/clipboard.ts ***!
  \****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ClipboardPlugin; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

var getCopiedText = function (textBlocks, startOffset, endOffset) {
    if (!textBlocks.length) {
        return undefined;
    }
    var excludingLastLineLength = textBlocks.slice(0, -1).join('').length + textBlocks.length - 1;
    return textBlocks.join('\n').slice(startOffset, excludingLastLineLength + endOffset);
};
function ClipboardPlugin() {
    var clipboardPlugin = {
        onCopy: function (event, editor) {
            event.preventDefault();
            var _a = editor.value, document = _a.document, selection = _a.selection;
            var startOffset = selection.start.offset, endOffset = selection.end.offset;
            var selectedBlocks = document
                .getLeafBlocksAtRange(selection)
                .toArray()
                .map(function (block) { return block.text; });
            var copiedText = getCopiedText(selectedBlocks, startOffset, endOffset);
            if (copiedText) {
                event.clipboardData.setData('Text', copiedText);
            }
            return true;
        },
        onPaste: function (event, editor) {
            var e_1, _a;
            event.preventDefault();
            var pastedValue = event.clipboardData.getData('Text');
            var lines = pastedValue.split('\n');
            if (lines.length) {
                editor.insertText(lines[0]);
                try {
                    for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](lines.slice(1)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var line = _c.value;
                        editor.splitBlock().insertText(line);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
            return true;
        },
    };
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, clipboardPlugin, { onCut: function (event, editor) {
            clipboardPlugin.onCopy(event, editor);
            editor.deleteAtRange(editor.value.selection);
            return true;
        } });
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/indentation.ts":
/*!******************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/indentation.ts ***!
  \******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return IndentationPlugin; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var slate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! slate */ "./node_modules/slate/lib/slate.es.js");
/* harmony import */ var is_hotkey__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! is-hotkey */ "./node_modules/is-hotkey/lib/index.js");
/* harmony import */ var is_hotkey__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(is_hotkey__WEBPACK_IMPORTED_MODULE_2__);



var isIndentLeftHotkey = Object(is_hotkey__WEBPACK_IMPORTED_MODULE_2__["isKeyHotkey"])('mod+[');
var isShiftTabHotkey = Object(is_hotkey__WEBPACK_IMPORTED_MODULE_2__["isKeyHotkey"])('shift+tab');
var isIndentRightHotkey = Object(is_hotkey__WEBPACK_IMPORTED_MODULE_2__["isKeyHotkey"])('mod+]');
var SLATE_TAB = '  ';
var handleTabKey = function (event, editor, next) {
    var _a = editor.value, startBlock = _a.startBlock, endBlock = _a.endBlock, _b = _a.selection, _c = _b.start, startOffset = _c.offset, startKey = _c.key, _d = _b.end, endOffset = _d.offset, endKey = _d.key;
    var first = startBlock.getFirstText();
    var startBlockIsSelected = startOffset === 0 && startKey === first.key && endOffset === first.text.length && endKey === first.key;
    if (startBlockIsSelected || !startBlock.equals(endBlock)) {
        handleIndent(editor, 'right');
    }
    else {
        editor.insertText(SLATE_TAB);
    }
};
var handleIndent = function (editor, indentDirection) {
    var e_1, _a, e_2, _b;
    var curSelection = editor.value.selection;
    var selectedBlocks = editor.value.document.getLeafBlocksAtRange(curSelection).toArray();
    if (indentDirection === 'left') {
        try {
            for (var selectedBlocks_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](selectedBlocks), selectedBlocks_1_1 = selectedBlocks_1.next(); !selectedBlocks_1_1.done; selectedBlocks_1_1 = selectedBlocks_1.next()) {
                var block = selectedBlocks_1_1.value;
                var blockWhitespace = block.text.length - block.text.trimLeft().length;
                var textKey = block.getFirstText().key;
                var rangeProperties = {
                    anchor: {
                        key: textKey,
                        offset: blockWhitespace,
                        path: [],
                    },
                    focus: {
                        key: textKey,
                        offset: blockWhitespace,
                        path: [],
                    },
                };
                editor.deleteBackwardAtRange(slate__WEBPACK_IMPORTED_MODULE_1__["Range"].create(rangeProperties), Math.min(SLATE_TAB.length, blockWhitespace));
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (selectedBlocks_1_1 && !selectedBlocks_1_1.done && (_a = selectedBlocks_1.return)) _a.call(selectedBlocks_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    else {
        var startText = editor.value.startText;
        var textBeforeCaret = startText.text.slice(0, curSelection.start.offset);
        var isWhiteSpace = /^\s*$/.test(textBeforeCaret);
        try {
            for (var selectedBlocks_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](selectedBlocks), selectedBlocks_2_1 = selectedBlocks_2.next(); !selectedBlocks_2_1.done; selectedBlocks_2_1 = selectedBlocks_2.next()) {
                var block = selectedBlocks_2_1.value;
                editor.insertTextByKey(block.getFirstText().key, 0, SLATE_TAB);
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (selectedBlocks_2_1 && !selectedBlocks_2_1.done && (_b = selectedBlocks_2.return)) _b.call(selectedBlocks_2);
            }
            finally { if (e_2) throw e_2.error; }
        }
        if (isWhiteSpace) {
            editor.moveStartBackward(SLATE_TAB.length);
        }
    }
};
// Clears the rest of the line after the caret
function IndentationPlugin() {
    return {
        onKeyDown: function (event, editor, next) {
            if (isIndentLeftHotkey(event) || isShiftTabHotkey(event)) {
                event.preventDefault();
                handleIndent(editor, 'left');
            }
            else if (isIndentRightHotkey(event)) {
                event.preventDefault();
                handleIndent(editor, 'right');
            }
            else if (event.key === 'Tab') {
                event.preventDefault();
                handleTabKey(event, editor, next);
            }
            else {
                return next();
            }
            return true;
        },
    };
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/newline.ts":
/*!**************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/newline.ts ***!
  \**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return NewlinePlugin; });
function getIndent(text) {
    var offset = text.length - text.trimLeft().length;
    if (offset) {
        var indent = text[0];
        while (--offset) {
            indent += text[0];
        }
        return indent;
    }
    return '';
}
function NewlinePlugin() {
    return {
        onKeyDown: function (event, editor, next) {
            var value = editor.value;
            if (value.selection.isExpanded) {
                return next();
            }
            if (event.key === 'Enter' && event.shiftKey) {
                event.preventDefault();
                var startBlock = value.startBlock;
                var currentLineText = startBlock.text;
                var indent = getIndent(currentLineText);
                return editor
                    .splitBlock()
                    .insertText(indent)
                    .focus();
            }
            return next();
        },
    };
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/runner.ts":
/*!*************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/runner.ts ***!
  \*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RunnerPlugin; });
function RunnerPlugin(_a) {
    var handler = _a.handler;
    return {
        onKeyDown: function (event, editor, next) {
            // Handle enter
            if (handler && event.key === 'Enter' && !event.shiftKey) {
                // Submit on Enter
                event.preventDefault();
                handler(event);
                return true;
            }
            return next();
        },
    };
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/selection_shortcuts.ts":
/*!**************************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/selection_shortcuts.ts ***!
  \**************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SelectionShortcutsPlugin; });
/* harmony import */ var is_hotkey__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! is-hotkey */ "./node_modules/is-hotkey/lib/index.js");
/* harmony import */ var is_hotkey__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(is_hotkey__WEBPACK_IMPORTED_MODULE_0__);

var isSelectLineHotkey = Object(is_hotkey__WEBPACK_IMPORTED_MODULE_0__["isKeyHotkey"])('mod+l');
// Clears the rest of the line after the caret
function SelectionShortcutsPlugin() {
    return {
        onKeyDown: function (event, editor, next) {
            if (isSelectLineHotkey(event)) {
                event.preventDefault();
                var _a = editor.value, focusBlock = _a.focusBlock, document = _a.document;
                editor.moveAnchorToStartOfBlock();
                var nextBlock = document.getNextBlock(focusBlock.key);
                if (nextBlock) {
                    editor.moveFocusToStartOfNextBlock();
                }
                else {
                    editor.moveFocusToEndOfText();
                }
            }
            else {
                return next();
            }
            return true;
        },
    };
}


/***/ }),

/***/ "./public/app/features/explore/slate-plugins/suggestions.tsx":
/*!*******************************************************************!*\
  !*** ./public/app/features/explore/slate-plugins/suggestions.tsx ***!
  \*******************************************************************/
/*! exports provided: TYPEAHEAD_DEBOUNCE, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TYPEAHEAD_DEBOUNCE", function() { return TYPEAHEAD_DEBOUNCE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SuggestionsPlugin; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash/debounce */ "./node_modules/lodash/debounce.js");
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash_debounce__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash/sortBy */ "./node_modules/lodash/sortBy.js");
/* harmony import */ var lodash_sortBy__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash_sortBy__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _grafana_ui_src_slate_plugins_slate_prism_TOKEN_MARK__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui/src/slate-plugins/slate-prism/TOKEN_MARK */ "./packages/grafana-ui/src/slate-plugins/slate-prism/TOKEN_MARK.ts");
/* harmony import */ var _Typeahead__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Typeahead */ "./public/app/features/explore/Typeahead.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
var _this = undefined;







var TYPEAHEAD_DEBOUNCE = 100;
var state = {
    groupedItems: [],
    typeaheadPrefix: '',
    typeaheadContext: '',
    typeaheadText: '',
};
function SuggestionsPlugin(_a) {
    var onTypeahead = _a.onTypeahead, cleanText = _a.cleanText, onWillApplySuggestion = _a.onWillApplySuggestion, syntax = _a.syntax, portalOrigin = _a.portalOrigin, component = _a.component;
    return {
        onBlur: function (event, editor, next) {
            state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { groupedItems: [] });
            return next();
        },
        onClick: function (event, editor, next) {
            state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { groupedItems: [] });
            return next();
        },
        onKeyDown: function (event, editor, next) {
            var currentSuggestions = state.groupedItems;
            var hasSuggestions = currentSuggestions.length;
            switch (event.key) {
                case 'Escape': {
                    if (hasSuggestions) {
                        event.preventDefault();
                        state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { groupedItems: [] });
                        // Bogus edit to re-render editor
                        return editor.insertText('');
                    }
                    break;
                }
                case 'ArrowDown':
                case 'ArrowUp':
                    if (hasSuggestions) {
                        event.preventDefault();
                        component.typeaheadRef.moveMenuIndex(event.key === 'ArrowDown' ? 1 : -1);
                        return;
                    }
                    break;
                case 'Enter':
                case 'Tab': {
                    if (hasSuggestions) {
                        event.preventDefault();
                        component.typeaheadRef.insertSuggestion();
                        return handleTypeahead(event, editor, onTypeahead, cleanText);
                    }
                    break;
                }
                default: {
                    handleTypeahead(event, editor, onTypeahead, cleanText);
                    break;
                }
            }
            return next();
        },
        commands: {
            selectSuggestion: function (editor, suggestion) {
                var suggestions = state.groupedItems;
                if (!suggestions || !suggestions.length) {
                    return editor;
                }
                // @ts-ignore
                return editor.applyTypeahead(suggestion);
            },
            applyTypeahead: function (editor, suggestion) {
                var suggestionText = suggestion.insertText || suggestion.label;
                var preserveSuffix = suggestion.kind === 'function';
                var move = suggestion.move || 0;
                var typeaheadPrefix = state.typeaheadPrefix, typeaheadText = state.typeaheadText, typeaheadContext = state.typeaheadContext;
                if (onWillApplySuggestion) {
                    suggestionText = onWillApplySuggestion(suggestionText, {
                        groupedItems: state.groupedItems,
                        typeaheadContext: typeaheadContext,
                        typeaheadPrefix: typeaheadPrefix,
                        typeaheadText: typeaheadText,
                    });
                }
                // Remove the current, incomplete text and replace it with the selected suggestion
                var backward = suggestion.deleteBackwards || typeaheadPrefix.length;
                var text = cleanText ? cleanText(typeaheadText) : typeaheadText;
                var suffixLength = text.length - typeaheadPrefix.length;
                var offset = typeaheadText.indexOf(typeaheadPrefix);
                var midWord = typeaheadPrefix && ((suffixLength > 0 && offset > -1) || suggestionText === typeaheadText);
                var forward = midWord && !preserveSuffix ? suffixLength + offset : 0;
                // If new-lines, apply suggestion as block
                if (suggestionText.match(/\n/)) {
                    var fragment = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["makeFragment"])(suggestionText);
                    return editor
                        .deleteBackward(backward)
                        .deleteForward(forward)
                        .insertFragment(fragment)
                        .focus();
                }
                state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { groupedItems: [] });
                return editor
                    .deleteBackward(backward)
                    .deleteForward(forward)
                    .insertText(suggestionText)
                    .moveForward(move)
                    .focus();
            },
        },
        renderEditor: function (props, editor, next) {
            if (editor.value.selection.isExpanded) {
                return next();
            }
            var children = next();
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                children,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Typeahead__WEBPACK_IMPORTED_MODULE_5__["TypeaheadWithTheme"], { menuRef: function (el) { return (component.typeaheadRef = el); }, origin: portalOrigin, prefix: state.typeaheadPrefix, isOpen: !!state.groupedItems.length, groupedItems: state.groupedItems, 
                    //@ts-ignore
                    onSelectSuggestion: editor.selectSuggestion })));
        },
    };
}
var handleTypeahead = lodash_debounce__WEBPACK_IMPORTED_MODULE_2___default()(function (event, editor, onTypeahead, cleanText) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    var value, selection, parentBlock, myOffset, decorations, filteredDecorations, labelKeyDec, labelKey, wrapperClasses, text, prefix, labelValueMatch, _a, suggestions, context, filteredSuggestions;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
        switch (_b.label) {
            case 0:
                if (!onTypeahead) {
                    return [2 /*return*/, null];
                }
                value = editor.value;
                selection = value.selection;
                parentBlock = value.document.getClosestBlock(value.focusBlock.key);
                myOffset = value.selection.start.offset - 1;
                decorations = parentBlock.getDecorations(editor);
                filteredDecorations = decorations
                    .filter(function (decoration) {
                    return decoration.start.offset <= myOffset && decoration.end.offset > myOffset && decoration.type === _grafana_ui_src_slate_plugins_slate_prism_TOKEN_MARK__WEBPACK_IMPORTED_MODULE_4__["default"];
                })
                    .toArray();
                labelKeyDec = decorations
                    .filter(function (decoration) {
                    return (decoration.end.offset <= myOffset &&
                        decoration.type === _grafana_ui_src_slate_plugins_slate_prism_TOKEN_MARK__WEBPACK_IMPORTED_MODULE_4__["default"] &&
                        decoration.data.get('className').includes('label-key'));
                })
                    .last();
                labelKey = labelKeyDec && value.focusText.text.slice(labelKeyDec.start.offset, labelKeyDec.end.offset);
                wrapperClasses = filteredDecorations
                    .map(function (decoration) { return decoration.data.get('className'); })
                    .join(' ')
                    .split(' ')
                    .filter(function (className) { return className.length; });
                text = value.focusText.text;
                prefix = text.slice(0, selection.focus.offset);
                if (filteredDecorations.length) {
                    text = value.focusText.text.slice(filteredDecorations[0].start.offset, filteredDecorations[0].end.offset);
                    prefix = value.focusText.text.slice(filteredDecorations[0].start.offset, selection.focus.offset);
                }
                labelValueMatch = prefix.match(/(?:!?=~?"?|")(.*)/);
                if (labelValueMatch) {
                    prefix = labelValueMatch[1];
                }
                else if (cleanText) {
                    prefix = cleanText(prefix);
                }
                return [4 /*yield*/, onTypeahead({
                        prefix: prefix,
                        text: text,
                        value: value,
                        wrapperClasses: wrapperClasses,
                        labelKey: labelKey,
                    })];
            case 1:
                _a = _b.sent(), suggestions = _a.suggestions, context = _a.context;
                filteredSuggestions = suggestions
                    .map(function (group) {
                    if (!group.items) {
                        return group;
                    }
                    if (prefix) {
                        // Filter groups based on prefix
                        if (!group.skipFilter) {
                            group.items = group.items.filter(function (c) { return (c.filterText || c.label).length >= prefix.length; });
                            if (group.prefixMatch) {
                                group.items = group.items.filter(function (c) { return (c.filterText || c.label).startsWith(prefix); });
                            }
                            else {
                                group.items = group.items.filter(function (c) { return (c.filterText || c.label).includes(prefix); });
                            }
                        }
                        // Filter out the already typed value (prefix) unless it inserts custom text
                        group.items = group.items.filter(function (c) { return c.insertText || (c.filterText || c.label) !== prefix; });
                    }
                    if (!group.skipSort) {
                        group.items = lodash_sortBy__WEBPACK_IMPORTED_MODULE_3___default()(group.items, function (item) { return item.sortText || item.label; });
                    }
                    return group;
                })
                    .filter(function (group) { return group.items && group.items.length; });
                state = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { groupedItems: filteredSuggestions, typeaheadPrefix: prefix, typeaheadContext: context, typeaheadText: text });
                // Bogus edit to force re-render
                return [2 /*return*/, editor.blur().focus()];
        }
    });
}); }, TYPEAHEAD_DEBOUNCE);


/***/ }),

/***/ "./public/app/features/explore/state/actionTypes.ts":
/*!**********************************************************!*\
  !*** ./public/app/features/explore/state/actionTypes.ts ***!
  \**********************************************************/
/*! exports provided: ActionTypes, addQueryRowAction, changeModeAction, changeQueryAction, changeSizeAction, changeRefreshIntervalAction, clearQueriesAction, clearOriginAction, highlightLogsExpressionAction, initializeExploreAction, loadDatasourceMissingAction, loadDatasourcePendingAction, loadDatasourceReadyAction, modifyQueriesAction, queryStartAction, queryEndedAction, queryStreamUpdatedAction, queryStoreSubscriptionAction, removeQueryRowAction, scanStartAction, scanStopAction, setQueriesAction, splitCloseAction, splitOpenAction, updateUIStateAction, toggleTableAction, toggleGraphAction, updateDatasourceInstanceAction, toggleLogLevelAction, resetExploreAction, queriesImportedAction, testDataSourcePendingAction, testDataSourceSuccessAction, testDataSourceFailureAction, loadExploreDatasources, historyUpdatedAction, setUrlReplacedAction, changeRangeAction, changeLoadingStateAction, setPausedStateAction */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addQueryRowAction", function() { return addQueryRowAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeModeAction", function() { return changeModeAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeQueryAction", function() { return changeQueryAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeSizeAction", function() { return changeSizeAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeRefreshIntervalAction", function() { return changeRefreshIntervalAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearQueriesAction", function() { return clearQueriesAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearOriginAction", function() { return clearOriginAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "highlightLogsExpressionAction", function() { return highlightLogsExpressionAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initializeExploreAction", function() { return initializeExploreAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDatasourceMissingAction", function() { return loadDatasourceMissingAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDatasourcePendingAction", function() { return loadDatasourcePendingAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadDatasourceReadyAction", function() { return loadDatasourceReadyAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modifyQueriesAction", function() { return modifyQueriesAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryStartAction", function() { return queryStartAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryEndedAction", function() { return queryEndedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryStreamUpdatedAction", function() { return queryStreamUpdatedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryStoreSubscriptionAction", function() { return queryStoreSubscriptionAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeQueryRowAction", function() { return removeQueryRowAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scanStartAction", function() { return scanStartAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scanStopAction", function() { return scanStopAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setQueriesAction", function() { return setQueriesAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "splitCloseAction", function() { return splitCloseAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "splitOpenAction", function() { return splitOpenAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateUIStateAction", function() { return updateUIStateAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggleTableAction", function() { return toggleTableAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggleGraphAction", function() { return toggleGraphAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateDatasourceInstanceAction", function() { return updateDatasourceInstanceAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toggleLogLevelAction", function() { return toggleLogLevelAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetExploreAction", function() { return resetExploreAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queriesImportedAction", function() { return queriesImportedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testDataSourcePendingAction", function() { return testDataSourcePendingAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testDataSourceSuccessAction", function() { return testDataSourceSuccessAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testDataSourceFailureAction", function() { return testDataSourceFailureAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadExploreDatasources", function() { return loadExploreDatasources; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "historyUpdatedAction", function() { return historyUpdatedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUrlReplacedAction", function() { return setUrlReplacedAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeRangeAction", function() { return changeRangeAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeLoadingStateAction", function() { return changeLoadingStateAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPausedStateAction", function() { return setPausedStateAction; });
/* harmony import */ var app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/redux/actionCreatorFactory */ "./public/app/core/redux/actionCreatorFactory.ts");

/**  Higher order actions
 *
 */
var ActionTypes;
(function (ActionTypes) {
    ActionTypes["SplitOpen"] = "explore/SPLIT_OPEN";
    ActionTypes["ResetExplore"] = "explore/RESET_EXPLORE";
})(ActionTypes || (ActionTypes = {}));
/**
 * Adds a query row after the row with the given index.
 */
var addQueryRowAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/ADD_QUERY_ROW').create();
/**
 * Change the mode of Explore.
 */
var changeModeAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CHANGE_MODE').create();
/**
 * Query change handler for the query row with the given index.
 * If `override` is reset the query modifications and run the queries. Use this to set queries via a link.
 */
var changeQueryAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CHANGE_QUERY').create();
/**
 * Keep track of the Explore container size, in particular the width.
 * The width will be used to calculate graph intervals (number of datapoints).
 */
var changeSizeAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CHANGE_SIZE').create();
/**
 * Change the time range of Explore. Usually called from the Timepicker or a graph interaction.
 */
var changeRefreshIntervalAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CHANGE_REFRESH_INTERVAL').create();
/**
 * Clear all queries and results.
 */
var clearQueriesAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CLEAR_QUERIES').create();
/**
 * Clear origin panel id.
 */
var clearOriginAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CLEAR_ORIGIN').create();
/**
 * Highlight expressions in the log results
 */
var highlightLogsExpressionAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/HIGHLIGHT_LOGS_EXPRESSION').create();
/**
 * Initialize Explore state with state from the URL and the React component.
 * Call this only on components for with the Explore state has not been initialized.
 */
var initializeExploreAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/INITIALIZE_EXPLORE').create();
/**
 * Display an error when no datasources have been configured
 */
var loadDatasourceMissingAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/LOAD_DATASOURCE_MISSING').create();
/**
 * Start the async process of loading a datasource to display a loading indicator
 */
var loadDatasourcePendingAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/LOAD_DATASOURCE_PENDING').create();
/**
 * Datasource loading was completed.
 */
var loadDatasourceReadyAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/LOAD_DATASOURCE_READY').create();
/**
 * Action to modify a query given a datasource-specific modifier action.
 * @param exploreId Explore area
 * @param modification Action object with a type, e.g., ADD_FILTER
 * @param index Optional query row index. If omitted, the modification is applied to all query rows.
 * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`.
 */
var modifyQueriesAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/MODIFY_QUERIES').create();
var queryStartAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/QUERY_START').create();
var queryEndedAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/QUERY_ENDED').create();
var queryStreamUpdatedAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/QUERY_STREAM_UPDATED').create();
var queryStoreSubscriptionAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/QUERY_STORE_SUBSCRIPTION').create();
/**
 * Remove query row of the given index, as well as associated query results.
 */
var removeQueryRowAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/REMOVE_QUERY_ROW').create();
/**
 * Start a scan for more results using the given scanner.
 * @param exploreId Explore area
 * @param scanner Function that a) returns a new time range and b) triggers a query run for the new range
 */
var scanStartAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SCAN_START').create();
/**
 * Stop any scanning for more results.
 */
var scanStopAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SCAN_STOP').create();
/**
 * Reset queries to the given queries. Any modifications will be discarded.
 * Use this action for clicks on query examples. Triggers a query run.
 */
var setQueriesAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SET_QUERIES').create();
/**
 * Close the split view and save URL state.
 */
var splitCloseAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SPLIT_CLOSE').create();
/**
 * Open the split view and copy the left state to be the right state.
 * The right state is automatically initialized.
 * The copy keeps all query modifications but wipes the query results.
 */
var splitOpenAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SPLIT_OPEN').create();
/**
 * Update state of Explores UI elements (panels visiblity and deduplication  strategy)
 */
var updateUIStateAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/UPDATE_UI_STATE').create();
/**
 * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
 */
var toggleTableAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/TOGGLE_TABLE').create();
/**
 * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
 */
var toggleGraphAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/TOGGLE_GRAPH').create();
/**
 * Updates datasource instance before datasouce loading has started
 */
var updateDatasourceInstanceAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/UPDATE_DATASOURCE_INSTANCE').create();
var toggleLogLevelAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/TOGGLE_LOG_LEVEL').create();
/**
 * Resets state for explore.
 */
var resetExploreAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/RESET_EXPLORE').create();
var queriesImportedAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/QueriesImported').create();
var testDataSourcePendingAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/TEST_DATASOURCE_PENDING').create();
var testDataSourceSuccessAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/TEST_DATASOURCE_SUCCESS').create();
var testDataSourceFailureAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/TEST_DATASOURCE_FAILURE').create();
var loadExploreDatasources = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/LOAD_EXPLORE_DATASOURCES').create();
var historyUpdatedAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/HISTORY_UPDATED').create();
var setUrlReplacedAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SET_URL_REPLACED').create();
var changeRangeAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/CHANGE_RANGE').create();
var changeLoadingStateAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('changeLoadingStateAction').create();
var setPausedStateAction = Object(app_core_redux_actionCreatorFactory__WEBPACK_IMPORTED_MODULE_0__["actionCreatorFactory"])('explore/SET_PAUSED_STATE').create();


/***/ }),

/***/ "./public/app/features/explore/state/reducers.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/explore/state/reducers.ts ***!
  \*******************************************************/
/*! exports provided: DEFAULT_RANGE, makeInitialUpdateState, makeExploreItemState, createEmptyQueryResponse, initialExploreItemState, initialExploreState, itemReducer, processQueryResponse, updateChildRefreshState, exploreReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_RANGE", function() { return DEFAULT_RANGE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeInitialUpdateState", function() { return makeInitialUpdateState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeExploreItemState", function() { return makeExploreItemState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createEmptyQueryResponse", function() { return createEmptyQueryResponse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialExploreItemState", function() { return initialExploreItemState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialExploreState", function() { return initialExploreState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "itemReducer", function() { return itemReducer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processQueryResponse", function() { return processQueryResponse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateChildRefreshState", function() { return updateChildRefreshState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exploreReducer", function() { return exploreReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");
/* harmony import */ var app_types_explore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/types/explore */ "./public/app/types/explore.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _actionTypes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./actionTypes */ "./public/app/features/explore/state/actionTypes.ts");
/* harmony import */ var app_core_redux__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/redux */ "./public/app/core/redux/index.ts");
/* harmony import */ var app_core_actions_location__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/actions/location */ "./public/app/core/actions/location.ts");
/* harmony import */ var app_core_table_model__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/table_model */ "./public/app/core/table_model.ts");
/* harmony import */ var _grafana_ui_src_components_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @grafana/ui/src/components/RefreshPicker/RefreshPicker */ "./packages/grafana-ui/src/components/RefreshPicker/RefreshPicker.tsx");
/* harmony import */ var _utils_ResultProcessor__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/ResultProcessor */ "./public/app/features/explore/utils/ResultProcessor.ts");











var DEFAULT_RANGE = {
    from: 'now-6h',
    to: 'now',
};
var makeInitialUpdateState = function () { return ({
    datasource: false,
    queries: false,
    range: false,
    mode: false,
    ui: false,
}); };
/**
 * Returns a fresh Explore area state
 */
var makeExploreItemState = function () { return ({
    StartPage: undefined,
    containerWidth: 0,
    datasourceInstance: null,
    requestedDatasourceName: null,
    datasourceError: null,
    datasourceLoading: null,
    datasourceMissing: false,
    exploreDatasources: [],
    history: [],
    queries: [],
    initialized: false,
    range: {
        from: null,
        to: null,
        raw: DEFAULT_RANGE,
    },
    absoluteRange: {
        from: null,
        to: null,
    },
    scanning: false,
    scanRange: null,
    showingGraph: true,
    showingTable: true,
    loading: false,
    queryKeys: [],
    urlState: null,
    update: makeInitialUpdateState(),
    latency: 0,
    supportedModes: [],
    mode: null,
    isLive: false,
    isPaused: false,
    urlReplaced: false,
    queryResponse: createEmptyQueryResponse(),
}); };
var createEmptyQueryResponse = function () { return ({
    state: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].NotStarted,
    request: {},
    series: [],
    error: null,
    timeRange: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["DefaultTimeRange"],
}); };
/**
 * Global Explore state that handles multiple Explore areas and the split state
 */
var initialExploreItemState = makeExploreItemState();
var initialExploreState = {
    split: null,
    left: initialExploreItemState,
    right: initialExploreItemState,
};
/**
 * Reducer for an Explore area, to be used by the global Explore reducer.
 */
var itemReducer = Object(app_core_redux__WEBPACK_IMPORTED_MODULE_6__["reducerFactory"])({})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["addQueryRowAction"],
    mapper: function (state, action) {
        var queries = state.queries;
        var _a = action.payload, index = _a.index, query = _a.query;
        // Add to queries, which will cause a new row to be rendered
        var nextQueries = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](queries.slice(0, index + 1), [tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query)], queries.slice(index + 1));
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: nextQueries, logsHighlighterExpressions: undefined, queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(nextQueries, state.datasourceInstance) });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["changeQueryAction"],
    mapper: function (state, action) {
        var queries = state.queries;
        var _a = action.payload, query = _a.query, index = _a.index;
        // Override path: queries are completely reset
        var nextQuery = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["generateNewKeyAndAddRefIdIfMissing"])(query, queries, index);
        var nextQueries = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](queries);
        nextQueries[index] = nextQuery;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: nextQueries, queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(nextQueries, state.datasourceInstance) });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["changeSizeAction"],
    mapper: function (state, action) {
        var containerWidth = action.payload.width;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { containerWidth: containerWidth });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["changeModeAction"],
    mapper: function (state, action) {
        var mode = action.payload.mode;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { mode: mode });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["changeRefreshIntervalAction"],
    mapper: function (state, action) {
        var refreshInterval = action.payload.refreshInterval;
        var live = Object(_grafana_ui_src_components_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_9__["isLive"])(refreshInterval);
        var sortOrder = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["refreshIntervalToSortOrder"])(refreshInterval);
        var logsResult = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["sortLogsResult"])(state.logsResult, sortOrder);
        if (Object(_grafana_ui_src_components_RefreshPicker_RefreshPicker__WEBPACK_IMPORTED_MODULE_9__["isLive"])(state.refreshInterval) && !live) {
            Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["stopQueryState"])(state.querySubscription);
        }
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { refreshInterval: refreshInterval, queryResponse: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.queryResponse, { state: live ? _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Streaming : _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].NotStarted }), isLive: live, isPaused: live ? false : state.isPaused, loading: live, logsResult: logsResult });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["clearQueriesAction"],
    mapper: function (state) {
        var queries = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["ensureQueries"])();
        Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["stopQueryState"])(state.querySubscription);
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: queries.slice(), graphResult: null, tableResult: null, logsResult: null, showingStartPage: Boolean(state.StartPage), queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(queries, state.datasourceInstance), queryResponse: createEmptyQueryResponse(), loading: false });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["clearOriginAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { originPanelId: undefined });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["highlightLogsExpressionAction"],
    mapper: function (state, action) {
        var expressions = action.payload.expressions;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { logsHighlighterExpressions: expressions });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["initializeExploreAction"],
    mapper: function (state, action) {
        var _a = action.payload, containerWidth = _a.containerWidth, eventBridge = _a.eventBridge, queries = _a.queries, range = _a.range, mode = _a.mode, ui = _a.ui, originPanelId = _a.originPanelId;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { containerWidth: containerWidth,
            eventBridge: eventBridge,
            range: range,
            mode: mode,
            queries: queries, initialized: true, queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(queries, state.datasourceInstance) }, ui, { originPanelId: originPanelId, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["updateDatasourceInstanceAction"],
    mapper: function (state, action) {
        var datasourceInstance = action.payload.datasourceInstance;
        var _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](getModesForDatasource(datasourceInstance, state.mode), 2), supportedModes = _a[0], mode = _a[1];
        var originPanelId = state.urlState && state.urlState.originPanelId;
        // Custom components
        var StartPage = datasourceInstance.components.ExploreStartPage;
        Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["stopQueryState"])(state.querySubscription);
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasourceInstance: datasourceInstance, graphResult: null, tableResult: null, logsResult: null, latency: 0, queryResponse: createEmptyQueryResponse(), loading: false, StartPage: StartPage, showingStartPage: Boolean(StartPage), queryKeys: [], supportedModes: supportedModes,
            mode: mode,
            originPanelId: originPanelId });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["loadDatasourceMissingAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasourceMissing: true, datasourceLoading: false, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["loadDatasourcePendingAction"],
    mapper: function (state, action) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasourceLoading: true, requestedDatasourceName: action.payload.requestedDatasourceName });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["loadDatasourceReadyAction"],
    mapper: function (state, action) {
        var history = action.payload.history;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { history: history, datasourceLoading: false, datasourceMissing: false, logsHighlighterExpressions: undefined, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["modifyQueriesAction"],
    mapper: function (state, action) {
        var queries = state.queries;
        var _a = action.payload, modification = _a.modification, index = _a.index, modifier = _a.modifier;
        var nextQueries;
        if (index === undefined) {
            // Modify all queries
            nextQueries = queries.map(function (query, i) {
                var nextQuery = modifier(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query), modification);
                return Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["generateNewKeyAndAddRefIdIfMissing"])(nextQuery, queries, i);
            });
        }
        else {
            // Modify query only at index
            nextQueries = queries.map(function (query, i) {
                if (i === index) {
                    var nextQuery = modifier(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query), modification);
                    return Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["generateNewKeyAndAddRefIdIfMissing"])(nextQuery, queries, i);
                }
                return query;
            });
        }
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: nextQueries, queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(nextQueries, state.datasourceInstance) });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["queryStartAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { latency: 0, queryResponse: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.queryResponse, { state: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Loading, error: null }), loading: true, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["removeQueryRowAction"],
    mapper: function (state, action) {
        var queries = state.queries, queryKeys = state.queryKeys;
        var index = action.payload.index;
        if (queries.length <= 1) {
            return state;
        }
        var nextQueries = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](queries.slice(0, index), queries.slice(index + 1));
        var nextQueryKeys = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](queryKeys.slice(0, index), queryKeys.slice(index + 1));
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: nextQueries, logsHighlighterExpressions: undefined, queryKeys: nextQueryKeys });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["scanStartAction"],
    mapper: function (state, action) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { scanning: true });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["scanStopAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { scanning: false, scanRange: undefined, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["setQueriesAction"],
    mapper: function (state, action) {
        var queries = action.payload.queries;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: queries.slice(), queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(queries, state.datasourceInstance) });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["updateUIStateAction"],
    mapper: function (state, action) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, action.payload);
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["toggleGraphAction"],
    mapper: function (state) {
        var showingGraph = !state.showingGraph;
        if (showingGraph) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { showingGraph: showingGraph });
        }
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { showingGraph: showingGraph, graphResult: null });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["toggleTableAction"],
    mapper: function (state) {
        var showingTable = !state.showingTable;
        if (showingTable) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { showingTable: showingTable });
        }
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { showingTable: showingTable, tableResult: new app_core_table_model__WEBPACK_IMPORTED_MODULE_8__["default"]() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["queriesImportedAction"],
    mapper: function (state, action) {
        var queries = action.payload.queries;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queries: queries, queryKeys: Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["getQueryKeys"])(queries, state.datasourceInstance) });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["toggleLogLevelAction"],
    mapper: function (state, action) {
        var hiddenLogLevels = action.payload.hiddenLogLevels;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hiddenLogLevels: Array.from(hiddenLogLevels) });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["testDataSourcePendingAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasourceError: null });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["testDataSourceSuccessAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasourceError: null });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["testDataSourceFailureAction"],
    mapper: function (state, action) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { datasourceError: action.payload.error, graphResult: undefined, tableResult: undefined, logsResult: undefined, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["loadExploreDatasources"],
    mapper: function (state, action) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { exploreDatasources: action.payload.exploreDatasources });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["historyUpdatedAction"],
    mapper: function (state, action) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { history: action.payload.history });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["setUrlReplacedAction"],
    mapper: function (state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { urlReplaced: true });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["changeRangeAction"],
    mapper: function (state, action) {
        var _a = action.payload, range = _a.range, absoluteRange = _a.absoluteRange;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { range: range,
            absoluteRange: absoluteRange, update: makeInitialUpdateState() });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["changeLoadingStateAction"],
    mapper: function (state, action) {
        var loadingState = action.payload.loadingState;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { queryResponse: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.queryResponse, { state: loadingState }), loading: loadingState === _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Loading || loadingState === _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Streaming });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["setPausedStateAction"],
    mapper: function (state, action) {
        var isPaused = action.payload.isPaused;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { isPaused: isPaused });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["queryStoreSubscriptionAction"],
    mapper: function (state, action) {
        var querySubscription = action.payload.querySubscription;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { querySubscription: querySubscription });
    },
})
    .addMapper({
    filter: _actionTypes__WEBPACK_IMPORTED_MODULE_5__["queryStreamUpdatedAction"],
    mapper: function (state, action) {
        return processQueryResponse(state, action);
    },
})
    .create();
var processQueryResponse = function (state, action) {
    var response = action.payload.response;
    var request = response.request, loadingState = response.state, series = response.series, error = response.error;
    if (error) {
        if (error.cancelled) {
            return state;
        }
        // For Angular editors
        state.eventBridge.emit('data-error', error);
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { loading: false, queryResponse: response, graphResult: null, tableResult: null, logsResult: null, showingStartPage: false, update: makeInitialUpdateState() });
    }
    var latency = request.endTime ? request.endTime - request.startTime : 0;
    var processor = new _utils_ResultProcessor__WEBPACK_IMPORTED_MODULE_10__["ResultProcessor"](state, series, request.intervalMs);
    var graphResult = processor.getGraphResult();
    var tableResult = processor.getTableResult();
    var logsResult = processor.getLogsResult();
    // Send legacy data to Angular editors
    if (state.datasourceInstance.components.QueryCtrl) {
        var legacy = series.map(function (v) { return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["toLegacyResponseData"])(v); });
        state.eventBridge.emit('data-received', legacy);
    }
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { latency: latency, queryResponse: response, graphResult: graphResult,
        tableResult: tableResult,
        logsResult: logsResult, loading: loadingState === _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Loading || loadingState === _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Streaming, showingStartPage: false, update: makeInitialUpdateState() });
};
var updateChildRefreshState = function (state, payload, exploreId) {
    var path = payload.path || '';
    var queryState = payload.query[exploreId];
    if (!queryState) {
        return state;
    }
    var urlState = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["parseUrlState"])(queryState);
    if (!state.urlState || path !== '/explore') {
        // we only want to refresh when browser back/forward
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { urlState: urlState, update: { datasource: false, queries: false, range: false, mode: false, ui: false } });
    }
    var datasource = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(urlState ? urlState.datasource : '', state.urlState.datasource) === false;
    var queries = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(urlState ? urlState.queries : [], state.urlState.queries) === false;
    var range = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(urlState ? urlState.range : DEFAULT_RANGE, state.urlState.range) === false;
    var mode = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(urlState ? urlState.mode : app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreMode"].Metrics, state.urlState.mode) === false;
    var ui = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(urlState ? urlState.ui : app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["DEFAULT_UI_STATE"], state.urlState.ui) === false;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { urlState: urlState, update: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.update, { datasource: datasource,
            queries: queries,
            range: range,
            mode: mode,
            ui: ui }) });
};
var getModesForDatasource = function (dataSource, currentMode) {
    // Temporary hack here. We want Loki to work in dashboards for which it needs to have metrics = true which is weird
    // for Explore.
    // TODO: need to figure out a better way to handle this situation
    var supportsGraph = dataSource.meta.name === 'Loki' ? false : dataSource.meta.metrics;
    var supportsLogs = dataSource.meta.logs;
    var mode = currentMode || app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreMode"].Metrics;
    var supportedModes = [];
    if (supportsGraph) {
        supportedModes.push(app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreMode"].Metrics);
    }
    if (supportsLogs) {
        supportedModes.push(app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreMode"].Logs);
    }
    if (supportedModes.length === 1) {
        mode = supportedModes[0];
    }
    return [supportedModes, mode];
};
/**
 * Global Explore reducer that handles multiple Explore areas (left and right).
 * Actions that have an `exploreId` get routed to the ExploreItemReducer.
 */
var exploreReducer = function (state, action) {
    var _a, _b, _c;
    if (state === void 0) { state = initialExploreState; }
    switch (action.type) {
        case _actionTypes__WEBPACK_IMPORTED_MODULE_5__["splitCloseAction"].type: {
            var itemId = action.payload.itemId;
            var targetSplit = {
                left: itemId === app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left ? state.right : state.left,
                right: initialExploreState.right,
            };
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, targetSplit, { split: false });
        }
        case _actionTypes__WEBPACK_IMPORTED_MODULE_5__["ActionTypes"].SplitOpen: {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { split: true, right: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, action.payload.itemState) });
        }
        case _actionTypes__WEBPACK_IMPORTED_MODULE_5__["ActionTypes"].ResetExplore: {
            if (action.payload.force || !Number.isInteger(state.left.originPanelId)) {
                return initialExploreState;
            }
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, initialExploreState, { left: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, initialExploreItemState, { queries: state.left.queries, originPanelId: state.left.originPanelId }) });
        }
        case app_core_actions_location__WEBPACK_IMPORTED_MODULE_7__["updateLocation"].type: {
            var query = action.payload.query;
            if (!query || !query[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left]) {
                return state;
            }
            var split = query[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right] ? true : false;
            var leftState = state[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left];
            var rightState = state[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right];
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, (_a = { split: split }, _a[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left] = updateChildRefreshState(leftState, action.payload, app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left), _a[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right] = updateChildRefreshState(rightState, action.payload, app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right), _a));
        }
        case _actionTypes__WEBPACK_IMPORTED_MODULE_5__["resetExploreAction"].type: {
            var leftState = state[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left];
            var rightState = state[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right];
            Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["stopQueryState"])(leftState.querySubscription);
            Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_2__["stopQueryState"])(rightState.querySubscription);
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, (_b = {}, _b[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left] = updateChildRefreshState(leftState, action.payload, app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].left), _b[app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right] = updateChildRefreshState(rightState, action.payload, app_types_explore__WEBPACK_IMPORTED_MODULE_3__["ExploreId"].right), _b));
        }
    }
    if (action.payload) {
        var exploreId = action.payload.exploreId;
        if (exploreId !== undefined) {
            // @ts-ignore
            var exploreItemState = state[exploreId];
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, (_c = {}, _c[exploreId] = itemReducer(exploreItemState, action), _c));
        }
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    explore: exploreReducer,
});


/***/ }),

/***/ "./public/app/features/explore/utils/ResultProcessor.ts":
/*!**************************************************************!*\
  !*** ./public/app/features/explore/utils/ResultProcessor.ts ***!
  \**************************************************************/
/*! exports provided: ResultProcessor, isTimeSeries */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResultProcessor", function() { return ResultProcessor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeSeries", function() { return isTimeSeries; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_types_explore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/types/explore */ "./public/app/types/explore.ts");
/* harmony import */ var app_core_table_model__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/table_model */ "./public/app/core/table_model.ts");
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");
/* harmony import */ var app_core_logs_model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/logs_model */ "./public/app/core/logs_model.ts");
/* harmony import */ var app_plugins_panel_graph2_getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/plugins/panel/graph2/getGraphSeriesModel */ "./public/app/plugins/panel/graph2/getGraphSeriesModel.ts");







var ResultProcessor = /** @class */ (function () {
    function ResultProcessor(state, dataFrames, intervalMs) {
        this.state = state;
        this.dataFrames = dataFrames;
        this.intervalMs = intervalMs;
    }
    ResultProcessor.prototype.getGraphResult = function () {
        if (this.state.mode !== app_types_explore__WEBPACK_IMPORTED_MODULE_2__["ExploreMode"].Metrics) {
            return null;
        }
        var onlyTimeSeries = this.dataFrames.filter(isTimeSeries);
        if (onlyTimeSeries.length === 0) {
            return null;
        }
        return Object(app_plugins_panel_graph2_getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_6__["getGraphSeriesModel"])(onlyTimeSeries, {}, { showBars: false, showLines: true, showPoints: false }, { asTable: false, isVisible: true, placement: 'under' });
    };
    ResultProcessor.prototype.getTableResult = function () {
        if (this.state.mode !== app_types_explore__WEBPACK_IMPORTED_MODULE_2__["ExploreMode"].Metrics) {
            return null;
        }
        // For now ignore time series
        // We can change this later, just need to figure out how to
        // Ignore time series only for prometheus
        var onlyTables = this.dataFrames.filter(function (frame) { return !isTimeSeries(frame); });
        if (onlyTables.length === 0) {
            return null;
        }
        var tables = onlyTables.map(function (frame) {
            var fields = frame.fields;
            var fieldCount = fields.length;
            var rowCount = frame.length;
            var columns = fields.map(function (field) { return ({
                text: field.name,
                type: field.type,
                filterable: field.config.filterable,
            }); });
            var rows = [];
            for (var i = 0; i < rowCount; i++) {
                var row = [];
                for (var j = 0; j < fieldCount; j++) {
                    row.push(frame.fields[j].values.get(i));
                }
                rows.push(row);
            }
            return new app_core_table_model__WEBPACK_IMPORTED_MODULE_3__["default"]({
                columns: columns,
                rows: rows,
                meta: frame.meta,
            });
        });
        return app_core_table_model__WEBPACK_IMPORTED_MODULE_3__["mergeTablesIntoModel"].apply(void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([new app_core_table_model__WEBPACK_IMPORTED_MODULE_3__["default"]()], tables));
    };
    ResultProcessor.prototype.getLogsResult = function () {
        if (this.state.mode !== app_types_explore__WEBPACK_IMPORTED_MODULE_2__["ExploreMode"].Logs) {
            return null;
        }
        var newResults = Object(app_core_logs_model__WEBPACK_IMPORTED_MODULE_5__["dataFrameToLogsModel"])(this.dataFrames, this.intervalMs);
        var sortOrder = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__["refreshIntervalToSortOrder"])(this.state.refreshInterval);
        var sortedNewResults = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__["sortLogsResult"])(newResults, sortOrder);
        var rows = sortedNewResults.rows;
        var series = sortedNewResults.series;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, sortedNewResults, { rows: rows, series: series });
    };
    return ResultProcessor;
}());

function isTimeSeries(frame) {
    if (frame.fields.length === 2) {
        if (frame.fields[1].type === _grafana_data__WEBPACK_IMPORTED_MODULE_1__["FieldType"].time) {
            return true;
        }
    }
    return false;
}


/***/ }),

/***/ "./public/app/features/explore/utils/typeahead.ts":
/*!********************************************************!*\
  !*** ./public/app/features/explore/utils/typeahead.ts ***!
  \********************************************************/
/*! exports provided: flattenGroupItems, calculateLongestLabel, calculateListSizes, calculateItemHeight, calculateListWidth, calculateListHeight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flattenGroupItems", function() { return flattenGroupItems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateLongestLabel", function() { return calculateLongestLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateListSizes", function() { return calculateListSizes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateItemHeight", function() { return calculateItemHeight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateListWidth", function() { return calculateListWidth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateListHeight", function() { return calculateListHeight; });
/* harmony import */ var calculate_size__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! calculate-size */ "./node_modules/calculate-size/lib/index.js");
/* harmony import */ var calculate_size__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(calculate_size__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");


var flattenGroupItems = function (groupedItems) {
    return groupedItems.reduce(function (all, current) {
        var titleItem = {
            label: current.label,
            kind: app_types__WEBPACK_IMPORTED_MODULE_1__["CompletionItemKind"].GroupTitle,
        };
        return all.concat(titleItem, current.items);
    }, []);
};
var calculateLongestLabel = function (allItems) {
    return allItems.reduce(function (longest, current) {
        return longest.length < current.label.length ? current.label : longest;
    }, '');
};
var calculateListSizes = function (theme, allItems, longestLabel) {
    var size = calculate_size__WEBPACK_IMPORTED_MODULE_0___default()(longestLabel, {
        font: theme.typography.fontFamily.monospace,
        fontSize: theme.typography.size.sm,
        fontWeight: 'normal',
    });
    var listWidth = calculateListWidth(size.width, theme);
    var itemHeight = calculateItemHeight(size.height, theme);
    var listHeight = calculateListHeight(itemHeight, allItems);
    return {
        listWidth: listWidth,
        listHeight: listHeight,
        itemHeight: itemHeight,
    };
};
var calculateItemHeight = function (longestLabelHeight, theme) {
    var horizontalPadding = parseInt(theme.spacing.sm, 10) * 2;
    var itemHeight = longestLabelHeight + horizontalPadding;
    return itemHeight;
};
var calculateListWidth = function (longestLabelWidth, theme) {
    var verticalPadding = parseInt(theme.spacing.sm, 10) + parseInt(theme.spacing.md, 10);
    var maxWidth = 800;
    var listWidth = Math.min(Math.max(longestLabelWidth + verticalPadding, 200), maxWidth);
    return listWidth;
};
var calculateListHeight = function (itemHeight, allItems) {
    var numberOfItemsToShow = Math.min(allItems.length, 10);
    var minHeight = 100;
    var totalHeight = numberOfItemsToShow * itemHeight;
    var listHeight = Math.max(totalHeight, minHeight);
    return listHeight;
};


/***/ }),

/***/ "./public/app/features/folders/CreateFolderCtrl.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/folders/CreateFolderCtrl.ts ***!
  \*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");


var CreateFolderCtrl = /** @class */ (function () {
    /** @ngInject */
    function CreateFolderCtrl(backendSrv, $location, validationSrv, navModelSrv) {
        this.backendSrv = backendSrv;
        this.$location = $location;
        this.validationSrv = validationSrv;
        this.title = '';
        this.titleTouched = false;
        this.navModel = navModelSrv.getNav('dashboards', 'manage-dashboards', 0);
    }
    CreateFolderCtrl.prototype.create = function () {
        var _this = this;
        if (this.hasValidationError) {
            return;
        }
        return this.backendSrv.createFolder({ title: this.title }).then(function (result) {
            app_core_app_events__WEBPACK_IMPORTED_MODULE_0__["default"].emit('alert-success', ['Folder Created', 'OK']);
            _this.$location.url(app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__["default"].stripBaseFromUrl(result.url));
        });
    };
    CreateFolderCtrl.prototype.titleChanged = function () {
        var _this = this;
        this.titleTouched = true;
        this.validationSrv
            .validateNewFolderName(this.title)
            .then(function () {
            _this.hasValidationError = false;
        })
            .catch(function (err) {
            _this.hasValidationError = true;
            _this.validationError = err.message;
        });
    };
    return CreateFolderCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (CreateFolderCtrl);


/***/ }),

/***/ "./public/app/features/folders/FolderDashboardsCtrl.ts":
/*!*************************************************************!*\
  !*** ./public/app/features/folders/FolderDashboardsCtrl.ts ***!
  \*************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _services_FolderPageLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./services/FolderPageLoader */ "./public/app/features/folders/services/FolderPageLoader.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");


var FolderDashboardsCtrl = /** @class */ (function () {
    /** @ngInject */
    function FolderDashboardsCtrl(backendSrv, navModelSrv, $routeParams, $location) {
        this.backendSrv = backendSrv;
        this.$routeParams = $routeParams;
        if (this.$routeParams.uid) {
            this.uid = $routeParams.uid;
            var loader = new _services_FolderPageLoader__WEBPACK_IMPORTED_MODULE_0__["FolderPageLoader"](this.backendSrv);
            loader.load(this, this.uid, 'manage-folder-dashboards').then(function (folder) {
                var url = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__["default"].stripBaseFromUrl(folder.url);
                if (url !== $location.path()) {
                    $location.path(url).replace();
                }
            });
        }
    }
    return FolderDashboardsCtrl;
}());
/* harmony default export */ __webpack_exports__["default"] = (FolderDashboardsCtrl);


/***/ }),

/***/ "./public/app/features/folders/services/FolderPageLoader.ts":
/*!******************************************************************!*\
  !*** ./public/app/features/folders/services/FolderPageLoader.ts ***!
  \******************************************************************/
/*! exports provided: FolderPageLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FolderPageLoader", function() { return FolderPageLoader; });
var FolderPageLoader = /** @class */ (function () {
    function FolderPageLoader(backendSrv) {
        this.backendSrv = backendSrv;
    }
    FolderPageLoader.prototype.load = function (ctrl, uid, activeChildId) {
        ctrl.navModel = {
            main: {
                icon: 'fa fa-folder-open',
                id: 'manage-folder',
                subTitle: 'Manage folder dashboards & permissions',
                url: '',
                text: '',
                breadcrumbs: [{ title: 'Dashboards', url: 'dashboards' }],
                children: [
                    {
                        active: activeChildId === 'manage-folder-dashboards',
                        icon: 'fa fa-fw fa-th-large',
                        id: 'manage-folder-dashboards',
                        text: 'Dashboards',
                        url: 'dashboards',
                    },
                    {
                        active: activeChildId === 'manage-folder-permissions',
                        icon: 'fa fa-fw fa-lock',
                        id: 'manage-folder-permissions',
                        text: 'Permissions',
                        url: 'dashboards/permissions',
                    },
                    {
                        active: activeChildId === 'manage-folder-settings',
                        icon: 'gicon gicon-cog',
                        id: 'manage-folder-settings',
                        text: 'Settings',
                        url: 'dashboards/settings',
                    },
                ],
            },
        };
        return this.backendSrv.getFolderByUid(uid).then(function (folder) {
            ctrl.folderId = folder.id;
            var folderTitle = folder.title;
            var folderUrl = folder.url;
            ctrl.navModel.main.text = folderTitle;
            var dashTab = ctrl.navModel.main.children.find(function (child) { return child.id === 'manage-folder-dashboards'; });
            dashTab.url = folderUrl;
            if (folder.canAdmin) {
                var permTab = ctrl.navModel.main.children.find(function (child) { return child.id === 'manage-folder-permissions'; });
                permTab.url = folderUrl + '/permissions';
                var settingsTab = ctrl.navModel.main.children.find(function (child) { return child.id === 'manage-folder-settings'; });
                settingsTab.url = folderUrl + '/settings';
            }
            else {
                ctrl.navModel.main.children = [dashTab];
            }
            return folder;
        });
    };
    return FolderPageLoader;
}());



/***/ }),

/***/ "./public/app/features/folders/state/actions.ts":
/*!******************************************************!*\
  !*** ./public/app/features/folders/state/actions.ts ***!
  \******************************************************/
/*! exports provided: ActionTypes, loadFolder, setFolderTitle, loadFolderPermissions, getFolderByUid, saveFolder, deleteFolder, getFolderPermissions, updateFolderPermission, removeFolderPermission, addFolderPermission */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFolder", function() { return loadFolder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setFolderTitle", function() { return setFolderTitle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFolderPermissions", function() { return loadFolderPermissions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFolderByUid", function() { return getFolderByUid; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveFolder", function() { return saveFolder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteFolder", function() { return deleteFolder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFolderPermissions", function() { return getFolderPermissions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFolderPermission", function() { return updateFolderPermission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeFolderPermission", function() { return removeFolderPermission; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addFolderPermission", function() { return addFolderPermission; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./navModel */ "./public/app/features/folders/state/navModel.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");





var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadFolder"] = "LOAD_FOLDER";
    ActionTypes["SetFolderTitle"] = "SET_FOLDER_TITLE";
    ActionTypes["SaveFolder"] = "SAVE_FOLDER";
    ActionTypes["LoadFolderPermissions"] = "LOAD_FOLDER_PERMISSONS";
})(ActionTypes || (ActionTypes = {}));
var loadFolder = function (folder) { return ({
    type: ActionTypes.LoadFolder,
    payload: folder,
}); };
var setFolderTitle = function (newTitle) { return ({
    type: ActionTypes.SetFolderTitle,
    payload: newTitle,
}); };
var loadFolderPermissions = function (items) { return ({
    type: ActionTypes.LoadFolderPermissions,
    payload: items,
}); };
function getFolderByUid(uid) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var folder;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().getFolderByUid(uid)];
                case 1:
                    folder = _a.sent();
                    dispatch(loadFolder(folder));
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_2__["updateNavIndex"])(Object(_navModel__WEBPACK_IMPORTED_MODULE_3__["buildNavModel"])(folder)));
                    return [2 /*return*/];
            }
        });
    }); };
}
function saveFolder(folder) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var res;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().put("/api/folders/" + folder.uid, {
                        title: folder.title,
                        version: folder.version,
                    })];
                case 1:
                    res = _a.sent();
                    // this should be redux action at some point
                    app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('alert-success', ['Folder saved']);
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_2__["updateLocation"])({ path: res.url + "/settings" }));
                    return [2 /*return*/];
            }
        });
    }); };
}
function deleteFolder(uid) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().deleteFolder(uid, true)];
                case 1:
                    _a.sent();
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_2__["updateLocation"])({ path: "dashboards" }));
                    return [2 /*return*/];
            }
        });
    }); };
}
function getFolderPermissions(uid) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var permissions;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/folders/" + uid + "/permissions")];
                case 1:
                    permissions = _a.sent();
                    dispatch(loadFolderPermissions(permissions));
                    return [2 /*return*/];
            }
        });
    }); };
}
function toUpdateItem(item) {
    return {
        userId: item.userId,
        teamId: item.teamId,
        role: item.role,
        permission: item.permission,
    };
}
function updateFolderPermission(itemToUpdate, level) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var folder, itemsToUpdate, _a, _b, item, updated;
        var e_1, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    folder = getStore().folder;
                    itemsToUpdate = [];
                    try {
                        for (_a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](folder.permissions), _b = _a.next(); !_b.done; _b = _a.next()) {
                            item = _b.value;
                            if (item.inherited) {
                                continue;
                            }
                            updated = toUpdateItem(item);
                            // if this is the item we want to update, update it's permission
                            if (itemToUpdate === item) {
                                updated.permission = level;
                            }
                            itemsToUpdate.push(updated);
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/folders/" + folder.uid + "/permissions", { items: itemsToUpdate })];
                case 1:
                    _d.sent();
                    return [4 /*yield*/, dispatch(getFolderPermissions(folder.uid))];
                case 2:
                    _d.sent();
                    return [2 /*return*/];
            }
        });
    }); };
}
function removeFolderPermission(itemToDelete) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var folder, itemsToUpdate, _a, _b, item;
        var e_2, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    folder = getStore().folder;
                    itemsToUpdate = [];
                    try {
                        for (_a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](folder.permissions), _b = _a.next(); !_b.done; _b = _a.next()) {
                            item = _b.value;
                            if (item.inherited || item === itemToDelete) {
                                continue;
                            }
                            itemsToUpdate.push(toUpdateItem(item));
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                    return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/folders/" + folder.uid + "/permissions", { items: itemsToUpdate })];
                case 1:
                    _d.sent();
                    return [4 /*yield*/, dispatch(getFolderPermissions(folder.uid))];
                case 2:
                    _d.sent();
                    return [2 /*return*/];
            }
        });
    }); };
}
function addFolderPermission(newItem) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var folder, itemsToUpdate, _a, _b, item;
        var e_3, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    folder = getStore().folder;
                    itemsToUpdate = [];
                    try {
                        for (_a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](folder.permissions), _b = _a.next(); !_b.done; _b = _a.next()) {
                            item = _b.value;
                            if (item.inherited) {
                                continue;
                            }
                            itemsToUpdate.push(toUpdateItem(item));
                        }
                    }
                    catch (e_3_1) { e_3 = { error: e_3_1 }; }
                    finally {
                        try {
                            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                        }
                        finally { if (e_3) throw e_3.error; }
                    }
                    itemsToUpdate.push({
                        userId: newItem.userId,
                        teamId: newItem.teamId,
                        role: newItem.role,
                        permission: newItem.permission,
                    });
                    return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/folders/" + folder.uid + "/permissions", { items: itemsToUpdate })];
                case 1:
                    _d.sent();
                    return [4 /*yield*/, dispatch(getFolderPermissions(folder.uid))];
                case 2:
                    _d.sent();
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/folders/state/navModel.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/folders/state/navModel.ts ***!
  \*******************************************************/
/*! exports provided: buildNavModel, getLoadingNav */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildNavModel", function() { return buildNavModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLoadingNav", function() { return getLoadingNav; });
function buildNavModel(folder) {
    return {
        icon: 'fa fa-folder-open',
        id: 'manage-folder',
        subTitle: 'Manage folder dashboards & permissions',
        url: '',
        text: folder.title,
        breadcrumbs: [{ title: 'Dashboards', url: 'dashboards' }],
        children: [
            {
                active: false,
                icon: 'fa fa-fw fa-th-large',
                id: "folder-dashboards-" + folder.uid,
                text: 'Dashboards',
                url: folder.url,
            },
            {
                active: false,
                icon: 'fa fa-fw fa-lock',
                id: "folder-permissions-" + folder.uid,
                text: 'Permissions',
                url: folder.url + "/permissions",
            },
            {
                active: false,
                icon: 'gicon gicon-cog',
                id: "folder-settings-" + folder.uid,
                text: 'Settings',
                url: folder.url + "/settings",
            },
        ],
    };
}
function getLoadingNav(tabIndex) {
    var main = buildNavModel({
        id: 1,
        uid: 'loading',
        title: 'Loading',
        url: 'url',
        canSave: false,
        version: 0,
    });
    main.children[tabIndex].active = true;
    return {
        main: main,
        node: main.children[tabIndex],
    };
}


/***/ }),

/***/ "./public/app/features/folders/state/reducers.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/folders/state/reducers.ts ***!
  \*******************************************************/
/*! exports provided: inititalState, folderReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inititalState", function() { return inititalState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "folderReducer", function() { return folderReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/folders/state/actions.ts");
/* harmony import */ var app_core_utils_acl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/acl */ "./public/app/core/utils/acl.ts");



var inititalState = {
    id: 0,
    uid: 'loading',
    title: 'loading',
    url: '',
    canSave: false,
    hasChanged: false,
    version: 1,
    permissions: [],
};
var folderReducer = function (state, action) {
    if (state === void 0) { state = inititalState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadFolder:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, action.payload, { hasChanged: false });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetFolderTitle:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { title: action.payload, hasChanged: action.payload.trim().length > 0 });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadFolderPermissions:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { permissions: Object(app_core_utils_acl__WEBPACK_IMPORTED_MODULE_2__["processAclItems"])(action.payload) });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    folder: folderReducer,
});


/***/ }),

/***/ "./public/app/features/manage-dashboards/DashboardImportCtrl.ts":
/*!**********************************************************************!*\
  !*** ./public/app/features/manage-dashboards/DashboardImportCtrl.ts ***!
  \**********************************************************************/
/*! exports provided: DashboardImportCtrl, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardImportCtrl", function() { return DashboardImportCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");




var DashboardImportCtrl = /** @class */ (function () {
    /** @ngInject */
    function DashboardImportCtrl(backendSrv, validationSrv, navModelSrv, $location, $routeParams) {
        this.backendSrv = backendSrv;
        this.validationSrv = validationSrv;
        this.$location = $location;
        this.navModel = navModelSrv.getNav('create', 'import');
        this.step = 1;
        this.nameExists = false;
        this.uidExists = false;
        this.autoGenerateUid = true;
        this.autoGenerateUidValue = 'auto-generated';
        this.folderId = $routeParams.folderId ? Number($routeParams.folderId) || 0 : null;
        this.initialFolderTitle = 'Select a folder';
        // check gnetId in url
        if ($routeParams.gnetId) {
            this.gnetUrl = $routeParams.gnetId;
            this.checkGnetDashboard();
        }
    }
    DashboardImportCtrl.prototype.onUpload = function (dash) {
        var e_1, _a;
        this.dash = dash;
        this.dash.id = null;
        this.step = 2;
        this.inputs = [];
        if (this.dash.__inputs) {
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.dash.__inputs), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var input = _c.value;
                    var inputModel = {
                        name: input.name,
                        label: input.label,
                        info: input.description,
                        value: input.value,
                        type: input.type,
                        pluginId: input.pluginId,
                        options: [],
                    };
                    if (input.type === 'datasource') {
                        this.setDatasourceOptions(input, inputModel);
                    }
                    else if (!inputModel.info) {
                        inputModel.info = 'Specify a string constant';
                    }
                    this.inputs.push(inputModel);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
        this.inputsValid = this.inputs.length === 0;
        this.titleChanged();
        this.uidChanged(true);
    };
    DashboardImportCtrl.prototype.setDatasourceOptions = function (input, inputModel) {
        var sources = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].datasources, function (val) {
            return val.type === input.pluginId;
        });
        if (sources.length === 0) {
            inputModel.info = 'No data sources of type ' + input.pluginName + ' found';
        }
        else if (!inputModel.info) {
            inputModel.info = 'Select a ' + input.pluginName + ' data source';
        }
        inputModel.options = sources.map(function (val) {
            return { text: val.name, value: val.name };
        });
    };
    DashboardImportCtrl.prototype.inputValueChanged = function () {
        var e_2, _a;
        this.inputsValid = true;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.inputs), _c = _b.next(); !_c.done; _c = _b.next()) {
                var input = _c.value;
                if (!input.value) {
                    this.inputsValid = false;
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
    };
    DashboardImportCtrl.prototype.titleChanged = function () {
        var _this = this;
        this.titleTouched = true;
        this.nameExists = false;
        this.validationSrv
            .validateNewDashboardName(this.folderId, this.dash.title)
            .then(function () {
            _this.nameExists = false;
            _this.hasNameValidationError = false;
        })
            .catch(function (err) {
            if (err.type === 'EXISTING') {
                _this.nameExists = true;
            }
            _this.hasNameValidationError = true;
            _this.nameValidationError = err.message;
        });
    };
    DashboardImportCtrl.prototype.uidChanged = function (initial) {
        var _this = this;
        this.uidExists = false;
        this.hasUidValidationError = false;
        if (initial === true && this.dash.uid) {
            this.autoGenerateUidValue = 'value set';
        }
        this.backendSrv
            // @ts-ignore
            .getDashboardByUid(this.dash.uid)
            .then(function (res) {
            _this.uidExists = true;
            _this.hasUidValidationError = true;
            _this.uidValidationError = "Dashboard named '" + res.dashboard.title + "' in folder '" + res.meta.folderTitle + "' has the same uid";
        })
            .catch(function (err) {
            err.isHandled = true;
        });
    };
    DashboardImportCtrl.prototype.onFolderChange = function (folder) {
        this.folderId = folder.id;
        this.titleChanged();
    };
    DashboardImportCtrl.prototype.onEnterFolderCreation = function () {
        this.inputsValid = false;
    };
    DashboardImportCtrl.prototype.onExitFolderCreation = function () {
        this.inputValueChanged();
    };
    DashboardImportCtrl.prototype.isValid = function () {
        return this.inputsValid && this.folderId !== null;
    };
    DashboardImportCtrl.prototype.saveDashboard = function () {
        var _this = this;
        var inputs = this.inputs.map(function (input) {
            return {
                name: input.name,
                type: input.type,
                pluginId: input.pluginId,
                value: input.value,
            };
        });
        return this.backendSrv
            .post('api/dashboards/import', {
            dashboard: this.dash,
            overwrite: true,
            inputs: inputs,
            folderId: this.folderId,
        })
            .then(function (res) {
            var dashUrl = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_3__["default"].stripBaseFromUrl(res.importedUrl);
            _this.$location.url(dashUrl);
        });
    };
    DashboardImportCtrl.prototype.loadJsonText = function () {
        try {
            this.parseError = '';
            var dash = JSON.parse(this.jsonText);
            this.onUpload(dash);
        }
        catch (err) {
            console.log(err);
            this.parseError = err.message;
            return;
        }
    };
    DashboardImportCtrl.prototype.checkGnetDashboard = function () {
        var _this = this;
        this.gnetError = '';
        var match = /(^\d+$)|dashboards\/(\d+)/.exec(this.gnetUrl);
        var dashboardId;
        if (match && match[1]) {
            dashboardId = match[1];
        }
        else if (match && match[2]) {
            dashboardId = match[2];
        }
        else {
            this.gnetError = 'Could not find dashboard';
        }
        return this.backendSrv
            .get('api/gnet/dashboards/' + dashboardId)
            .then(function (res) {
            _this.gnetInfo = res;
            // store reference to grafana.com
            res.json.gnetId = res.id;
            _this.onUpload(res.json);
        })
            .catch(function (err) {
            err.isHandled = true;
            _this.gnetError = err.data.message || err;
        });
    };
    DashboardImportCtrl.prototype.back = function () {
        this.gnetUrl = '';
        this.step = 1;
        this.gnetError = '';
        this.gnetInfo = '';
    };
    return DashboardImportCtrl;
}());

/* harmony default export */ __webpack_exports__["default"] = (DashboardImportCtrl);


/***/ }),

/***/ "./public/app/features/manage-dashboards/DashboardListCtrl.ts":
/*!********************************************************************!*\
  !*** ./public/app/features/manage-dashboards/DashboardListCtrl.ts ***!
  \********************************************************************/
/*! exports provided: DashboardListCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardListCtrl", function() { return DashboardListCtrl; });
var DashboardListCtrl = /** @class */ (function () {
    /** @ngInject */
    function DashboardListCtrl(navModelSrv) {
        this.navModel = navModelSrv.getNav('dashboards', 'manage-dashboards', 0);
    }
    return DashboardListCtrl;
}());



/***/ }),

/***/ "./public/app/features/manage-dashboards/SnapshotListCtrl.ts":
/*!*******************************************************************!*\
  !*** ./public/app/features/manage-dashboards/SnapshotListCtrl.ts ***!
  \*******************************************************************/
/*! exports provided: SnapshotListCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SnapshotListCtrl", function() { return SnapshotListCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


var SnapshotListCtrl = /** @class */ (function () {
    /** @ngInject */
    function SnapshotListCtrl($rootScope, backendSrv, navModelSrv, $location) {
        var _this = this;
        this.$rootScope = $rootScope;
        this.backendSrv = backendSrv;
        this.$location = $location;
        this.navModel = navModelSrv.getNav('dashboards', 'snapshots', 0);
        this.backendSrv.get('/api/dashboard/snapshots').then(function (result) {
            var baseUrl = _this.$location.absUrl().replace($location.url(), '');
            _this.snapshots = result.map(function (snapshot) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, snapshot, { url: snapshot.externalUrl || baseUrl + "/dashboard/snapshot/" + snapshot.key })); });
        });
    }
    SnapshotListCtrl.prototype.removeSnapshotConfirmed = function (snapshot) {
        var _this = this;
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.remove(this.snapshots, { key: snapshot.key });
        this.backendSrv.delete('/api/snapshots/' + snapshot.key).then(function () { }, function () {
            _this.snapshots.push(snapshot);
        });
    };
    SnapshotListCtrl.prototype.removeSnapshot = function (snapshot) {
        var _this = this;
        this.$rootScope.appEvent('confirm-modal', {
            title: 'Delete',
            text: 'Are you sure you want to delete snapshot ' + snapshot.name + '?',
            yesText: 'Delete',
            icon: 'fa-trash',
            onConfirm: function () {
                _this.removeSnapshotConfirmed(snapshot);
            },
        });
    };
    return SnapshotListCtrl;
}());



/***/ }),

/***/ "./public/app/features/manage-dashboards/components/MoveToFolderModal/MoveToFolderCtrl.ts":
/*!************************************************************************************************!*\
  !*** ./public/app/features/manage-dashboards/components/MoveToFolderModal/MoveToFolderCtrl.ts ***!
  \************************************************************************************************/
/*! exports provided: MoveToFolderCtrl, moveToFolderModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MoveToFolderCtrl", function() { return MoveToFolderCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moveToFolderModal", function() { return moveToFolderModal; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");


var MoveToFolderCtrl = /** @class */ (function () {
    /** @ngInject */
    function MoveToFolderCtrl(backendSrv) {
        this.backendSrv = backendSrv;
        this.isValidFolderSelection = true;
    }
    MoveToFolderCtrl.prototype.onFolderChange = function (folder) {
        this.folder = folder;
    };
    MoveToFolderCtrl.prototype.save = function () {
        var _this = this;
        return this.backendSrv.moveDashboards(this.dashboards, this.folder).then(function (result) {
            if (result.successCount > 0) {
                var header = "Dashboard" + (result.successCount === 1 ? '' : 's') + " Moved";
                var msg = result.successCount + " dashboard" + (result.successCount === 1 ? '' : 's') + " moved to " + _this.folder.title;
                app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].emit('alert-success', [header, msg]);
            }
            if (result.totalCount === result.alreadyInFolderCount) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].emit('alert-error', ['Error', "Dashboards already belongs to folder " + _this.folder.title]);
            }
            _this.dismiss();
            return _this.afterSave();
        });
    };
    MoveToFolderCtrl.prototype.onEnterFolderCreation = function () {
        this.isValidFolderSelection = false;
    };
    MoveToFolderCtrl.prototype.onExitFolderCreation = function () {
        this.isValidFolderSelection = true;
    };
    return MoveToFolderCtrl;
}());

function moveToFolderModal() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/manage-dashboards/components/MoveToFolderModal/template.html',
        controller: MoveToFolderCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            dismiss: '&',
            dashboards: '=',
            afterSave: '&',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('moveToFolderModal', moveToFolderModal);


/***/ }),

/***/ "./public/app/features/manage-dashboards/components/MoveToFolderModal/index.ts":
/*!*************************************************************************************!*\
  !*** ./public/app/features/manage-dashboards/components/MoveToFolderModal/index.ts ***!
  \*************************************************************************************/
/*! exports provided: MoveToFolderCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _MoveToFolderCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./MoveToFolderCtrl */ "./public/app/features/manage-dashboards/components/MoveToFolderModal/MoveToFolderCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MoveToFolderCtrl", function() { return _MoveToFolderCtrl__WEBPACK_IMPORTED_MODULE_0__["MoveToFolderCtrl"]; });




/***/ }),

/***/ "./public/app/features/manage-dashboards/components/UploadDashboard/index.ts":
/*!***********************************************************************************!*\
  !*** ./public/app/features/manage-dashboards/components/UploadDashboard/index.ts ***!
  \***********************************************************************************/
/*! exports provided: uploadDashboardDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _uploadDashboardDirective__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./uploadDashboardDirective */ "./public/app/features/manage-dashboards/components/UploadDashboard/uploadDashboardDirective.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "uploadDashboardDirective", function() { return _uploadDashboardDirective__WEBPACK_IMPORTED_MODULE_0__["uploadDashboardDirective"]; });




/***/ }),

/***/ "./public/app/features/manage-dashboards/components/UploadDashboard/uploadDashboardDirective.ts":
/*!******************************************************************************************************!*\
  !*** ./public/app/features/manage-dashboards/components/UploadDashboard/uploadDashboardDirective.ts ***!
  \******************************************************************************************************/
/*! exports provided: uploadDashboardDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uploadDashboardDirective", function() { return uploadDashboardDirective; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);



var template = "\n<input type=\"file\" id=\"dashupload\" name=\"dashupload\" class=\"hide\" onchange=\"angular.element(this).scope().file_selected\"/>\n<label class=\"btn btn-primary\" for=\"dashupload\">\n  {{btnText}}\n</label>\n";
/** @ngInject */
function uploadDashboardDirective(timer, $location) {
    return {
        restrict: 'E',
        template: template,
        scope: {
            onUpload: '&',
            btnText: '@?',
        },
        link: function (scope, elem) {
            scope.btnText = angular__WEBPACK_IMPORTED_MODULE_2___default.a.isDefined(scope.btnText) ? scope.btnText : 'Upload .json file';
            function file_selected(evt) {
                var files = evt.target.files; // FileList object
                var readerOnload = function () {
                    return function (e) {
                        var dash;
                        try {
                            dash = JSON.parse(e.target.result);
                        }
                        catch (err) {
                            console.log(err);
                            app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].emit('alert-error', ['Import failed', 'JSON -> JS Serialization failed: ' + err.message]);
                            return;
                        }
                        scope.$apply(function () {
                            scope.onUpload({ dash: dash });
                        });
                    };
                };
                var i = 0;
                var file = files[i];
                while (file) {
                    var reader = new FileReader();
                    reader.onload = readerOnload();
                    reader.readAsText(file);
                    i += 1;
                    file = files[i];
                }
            }
            var wnd = window;
            // Check for the various File API support.
            if (wnd.File && wnd.FileReader && wnd.FileList && wnd.Blob) {
                // Something
                elem[0].addEventListener('change', file_selected, false);
            }
            else {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_1__["default"].emit('alert-error', ['Oops', 'The HTML5 File APIs are not fully supported in this browser']);
            }
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('dashUpload', uploadDashboardDirective);


/***/ }),

/***/ "./public/app/features/manage-dashboards/index.ts":
/*!********************************************************!*\
  !*** ./public/app/features/manage-dashboards/index.ts ***!
  \********************************************************/
/*! exports provided: ValidationSrv, MoveToFolderCtrl, uploadDashboardDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _services_ValidationSrv__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./services/ValidationSrv */ "./public/app/features/manage-dashboards/services/ValidationSrv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValidationSrv", function() { return _services_ValidationSrv__WEBPACK_IMPORTED_MODULE_0__["ValidationSrv"]; });

/* harmony import */ var _components_MoveToFolderModal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/MoveToFolderModal */ "./public/app/features/manage-dashboards/components/MoveToFolderModal/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MoveToFolderCtrl", function() { return _components_MoveToFolderModal__WEBPACK_IMPORTED_MODULE_1__["MoveToFolderCtrl"]; });

/* harmony import */ var _components_UploadDashboard__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./components/UploadDashboard */ "./public/app/features/manage-dashboards/components/UploadDashboard/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "uploadDashboardDirective", function() { return _components_UploadDashboard__WEBPACK_IMPORTED_MODULE_2__["uploadDashboardDirective"]; });

/* harmony import */ var _DashboardListCtrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DashboardListCtrl */ "./public/app/features/manage-dashboards/DashboardListCtrl.ts");
/* harmony import */ var _SnapshotListCtrl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SnapshotListCtrl */ "./public/app/features/manage-dashboards/SnapshotListCtrl.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
// Services

// Components


// Controllers



app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('DashboardListCtrl', _DashboardListCtrl__WEBPACK_IMPORTED_MODULE_3__["DashboardListCtrl"]);
app_core_core_module__WEBPACK_IMPORTED_MODULE_5__["default"].controller('SnapshotListCtrl', _SnapshotListCtrl__WEBPACK_IMPORTED_MODULE_4__["SnapshotListCtrl"]);


/***/ }),

/***/ "./public/app/features/manage-dashboards/services/ValidationSrv.ts":
/*!*************************************************************************!*\
  !*** ./public/app/features/manage-dashboards/services/ValidationSrv.ts ***!
  \*************************************************************************/
/*! exports provided: ValidationSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValidationSrv", function() { return ValidationSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");


var hitTypes = {
    FOLDER: 'dash-folder',
    DASHBOARD: 'dash-db',
};
var ValidationSrv = /** @class */ (function () {
    /** @ngInject */
    function ValidationSrv($q, backendSrv) {
        this.$q = $q;
        this.backendSrv = backendSrv;
        this.rootName = 'general';
    }
    ValidationSrv.prototype.validateNewDashboardName = function (folderId, name) {
        return this.validate(folderId, name, 'A dashboard in this folder with the same name already exists');
    };
    ValidationSrv.prototype.validateNewFolderName = function (name) {
        return this.validate(0, name, 'A folder or dashboard in the general folder with the same name already exists');
    };
    ValidationSrv.prototype.validate = function (folderId, name, existingErrorMessage) {
        name = (name || '').trim();
        var nameLowerCased = name.toLowerCase();
        if (name.length === 0) {
            return this.$q.reject({
                type: 'REQUIRED',
                message: 'Name is required',
            });
        }
        if (folderId === 0 && nameLowerCased === this.rootName) {
            return this.$q.reject({
                type: 'EXISTING',
                message: 'This is a reserved name and cannot be used for a folder.',
            });
        }
        var deferred = this.$q.defer();
        var promises = [];
        promises.push(this.backendSrv.search({ type: hitTypes.FOLDER, folderIds: [folderId], query: name }));
        promises.push(this.backendSrv.search({ type: hitTypes.DASHBOARD, folderIds: [folderId], query: name }));
        this.$q.all(promises).then(function (res) {
            var e_1, _a;
            var hits = [];
            if (res.length > 0 && res[0].length > 0) {
                hits = res[0];
            }
            if (res.length > 1 && res[1].length > 0) {
                hits = hits.concat(res[1]);
            }
            try {
                for (var hits_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](hits), hits_1_1 = hits_1.next(); !hits_1_1.done; hits_1_1 = hits_1.next()) {
                    var hit = hits_1_1.value;
                    if (nameLowerCased === hit.title.toLowerCase()) {
                        deferred.reject({
                            type: 'EXISTING',
                            message: existingErrorMessage,
                        });
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (hits_1_1 && !hits_1_1.done && (_a = hits_1.return)) _a.call(hits_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            deferred.resolve();
        });
        return deferred.promise;
    };
    return ValidationSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('validationSrv', ValidationSrv);


/***/ }),

/***/ "./public/app/features/org/NewOrgCtrl.ts":
/*!***********************************************!*\
  !*** ./public/app/features/org/NewOrgCtrl.ts ***!
  \***********************************************/
/*! exports provided: NewOrgCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NewOrgCtrl", function() { return NewOrgCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");


var NewOrgCtrl = /** @class */ (function () {
    /** @ngInject */
    function NewOrgCtrl($scope, $http, backendSrv, navModelSrv) {
        $scope.navModel = navModelSrv.getNav('admin', 'global-orgs', 0);
        $scope.newOrg = { name: '' };
        $scope.createOrg = function () {
            backendSrv.post('/api/orgs/', $scope.newOrg).then(function (result) {
                backendSrv.post('/api/user/using/' + result.orgId).then(function () {
                    window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/org';
                });
            });
        };
    }
    return NewOrgCtrl;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.controllers').controller('NewOrgCtrl', NewOrgCtrl);


/***/ }),

/***/ "./public/app/features/org/SelectOrgCtrl.ts":
/*!**************************************************!*\
  !*** ./public/app/features/org/SelectOrgCtrl.ts ***!
  \**************************************************/
/*! exports provided: SelectOrgCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectOrgCtrl", function() { return SelectOrgCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");


var SelectOrgCtrl = /** @class */ (function () {
    /** @ngInject */
    function SelectOrgCtrl($scope, backendSrv, contextSrv) {
        contextSrv.sidemenu = false;
        $scope.navModel = {
            main: {
                icon: 'gicon gicon-branding',
                subTitle: 'Preferences',
                text: 'Select active organization',
            },
        };
        $scope.init = function () {
            $scope.getUserOrgs();
        };
        $scope.getUserOrgs = function () {
            backendSrv.get('/api/user/orgs').then(function (orgs) {
                $scope.orgs = orgs;
            });
        };
        $scope.setUsingOrg = function (org) {
            backendSrv.post('/api/user/using/' + org.orgId).then(function () {
                window.location.href = app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].appSubUrl + '/';
            });
        };
        $scope.init();
    }
    return SelectOrgCtrl;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.controllers').controller('SelectOrgCtrl', SelectOrgCtrl);


/***/ }),

/***/ "./public/app/features/org/UserInviteCtrl.ts":
/*!***************************************************!*\
  !*** ./public/app/features/org/UserInviteCtrl.ts ***!
  \***************************************************/
/*! exports provided: UserInviteCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserInviteCtrl", function() { return UserInviteCtrl; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var UserInviteCtrl = /** @class */ (function () {
    /** @ngInject */
    function UserInviteCtrl(backendSrv, navModelSrv, $location) {
        this.backendSrv = backendSrv;
        this.$location = $location;
        this.navModel = navModelSrv.getNav('cfg', 'users', 0);
        this.invite = {
            name: '',
            email: '',
            role: 'Editor',
            sendEmail: true,
        };
    }
    UserInviteCtrl.prototype.sendInvite = function () {
        var _this = this;
        if (!this.inviteForm.$valid) {
            return;
        }
        return this.backendSrv.post('/api/org/invites', this.invite).then(function () {
            _this.$location.path('org/users/');
        });
    };
    return UserInviteCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].controller('UserInviteCtrl', UserInviteCtrl);


/***/ }),

/***/ "./public/app/features/org/all.ts":
/*!****************************************!*\
  !*** ./public/app/features/org/all.ts ***!
  \****************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _SelectOrgCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SelectOrgCtrl */ "./public/app/features/org/SelectOrgCtrl.ts");
/* harmony import */ var _NewOrgCtrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NewOrgCtrl */ "./public/app/features/org/NewOrgCtrl.ts");
/* harmony import */ var _UserInviteCtrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./UserInviteCtrl */ "./public/app/features/org/UserInviteCtrl.ts");





/***/ }),

/***/ "./public/app/features/org/state/actions.ts":
/*!**************************************************!*\
  !*** ./public/app/features/org/state/actions.ts ***!
  \**************************************************/
/*! exports provided: ActionTypes, setOrganizationName, loadOrganization, updateOrganization */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setOrganizationName", function() { return setOrganizationName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadOrganization", function() { return loadOrganization; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateOrganization", function() { return updateOrganization; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");


var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadOrganization"] = "LOAD_ORGANIZATION";
    ActionTypes["SetOrganizationName"] = "SET_ORGANIZATION_NAME";
})(ActionTypes || (ActionTypes = {}));
var organizationLoaded = function (organization) { return ({
    type: ActionTypes.LoadOrganization,
    payload: organization,
}); };
var setOrganizationName = function (orgName) { return ({
    type: ActionTypes.SetOrganizationName,
    payload: orgName,
}); };
function loadOrganization() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var organizationResponse;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/org')];
                case 1:
                    organizationResponse = _a.sent();
                    dispatch(organizationLoaded(organizationResponse));
                    return [2 /*return*/, organizationResponse];
            }
        });
    }); };
}
function updateOrganization() {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var organization;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    organization = getStore().organization.organization;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().put('/api/org', { name: organization.name })];
                case 1:
                    _a.sent();
                    dispatch(loadOrganization());
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/org/state/reducers.ts":
/*!***************************************************!*\
  !*** ./public/app/features/org/state/reducers.ts ***!
  \***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/org/state/actions.ts");


var initialState = {
    organization: {},
};
var organizationReducer = function (state, action) {
    if (state === void 0) { state = initialState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadOrganization:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { organization: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetOrganizationName:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { organization: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state.organization, { name: action.payload }) });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    organization: organizationReducer,
});


/***/ }),

/***/ "./public/app/features/panel/all.ts":
/*!******************************************!*\
  !*** ./public/app/features/panel/all.ts ***!
  \******************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _panel_header__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./panel_header */ "./public/app/features/panel/panel_header.ts");
/* harmony import */ var _panel_directive__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./panel_directive */ "./public/app/features/panel/panel_directive.ts");
/* harmony import */ var _query_ctrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./query_ctrl */ "./public/app/features/panel/query_ctrl.ts");
/* harmony import */ var _panel_editor_tab__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./panel_editor_tab */ "./public/app/features/panel/panel_editor_tab.ts");
/* harmony import */ var _query_editor_row__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./query_editor_row */ "./public/app/features/panel/query_editor_row.ts");
/* harmony import */ var _repeat_option__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./repeat_option */ "./public/app/features/panel/repeat_option.ts");
/* harmony import */ var _panellinks_module__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./panellinks/module */ "./public/app/features/panel/panellinks/module.ts");









/***/ }),

/***/ "./public/app/features/panel/metrics_panel_ctrl.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/panel/metrics_panel_ctrl.ts ***!
  \*********************************************************/
/*! exports provided: MetricsPanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetricsPanelCtrl", function() { return MetricsPanelCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_features_panel_panel_ctrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/panel/panel_ctrl */ "./public/app/features/panel/panel_ctrl.ts");
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");
/* harmony import */ var app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/dashboard/utils/panel */ "./public/app/features/dashboard/utils/panel.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");







var MetricsPanelCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MetricsPanelCtrl, _super);
    function MetricsPanelCtrl($scope, $injector) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.useDataFrames = false;
        // Updates the response with information from the stream
        _this.panelDataObserver = {
            next: function (data) {
                if (data.state === _grafana_data__WEBPACK_IMPORTED_MODULE_6__["LoadingState"].Error) {
                    _this.loading = false;
                    _this.processDataError(data.error);
                    return;
                }
                // Ignore data in loading state
                if (data.state === _grafana_data__WEBPACK_IMPORTED_MODULE_6__["LoadingState"].Loading) {
                    _this.loading = true;
                    return;
                }
                if (data.request) {
                    var timeInfo = data.request.timeInfo;
                    if (timeInfo) {
                        _this.timeInfo = timeInfo;
                    }
                }
                if (data.timeRange) {
                    _this.range = data.timeRange;
                }
                if (_this.useDataFrames) {
                    _this.handleDataFrames(data.series);
                }
                else {
                    // Make the results look as if they came directly from a <6.2 datasource request
                    var legacy = data.series.map(function (v) { return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_6__["toLegacyResponseData"])(v); });
                    _this.handleQueryResult({ data: legacy });
                }
            },
        };
        _this.$q = $injector.get('$q');
        _this.contextSrv = $injector.get('contextSrv');
        _this.datasourceSrv = $injector.get('datasourceSrv');
        _this.timeSrv = $injector.get('timeSrv');
        _this.templateSrv = $injector.get('templateSrv');
        _this.scope = $scope;
        _this.panel.datasource = _this.panel.datasource || null;
        _this.events.on('refresh', _this.onMetricsPanelRefresh.bind(_this));
        _this.events.on('panel-teardown', _this.onPanelTearDown.bind(_this));
        return _this;
    }
    MetricsPanelCtrl.prototype.onPanelTearDown = function () {
        if (this.querySubscription) {
            this.querySubscription.unsubscribe();
            this.querySubscription = null;
        }
    };
    MetricsPanelCtrl.prototype.onMetricsPanelRefresh = function () {
        var _this = this;
        // ignore fetching data if another panel is in fullscreen
        if (this.otherPanelInFullscreenMode()) {
            return;
        }
        // if we have snapshot data use that
        if (this.panel.snapshotData) {
            this.updateTimeRange();
            var data_1 = this.panel.snapshotData;
            // backward compatibility
            if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isArray(data_1)) {
                data_1 = data_1.data;
            }
            // Defer panel rendering till the next digest cycle.
            // For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
            return this.$timeout(function () {
                _this.events.emit('data-snapshot-load', data_1);
            });
        }
        // clear loading/error state
        delete this.error;
        this.loading = true;
        // load datasource service
        return this.datasourceSrv
            .get(this.panel.datasource, this.panel.scopedVars)
            .then(this.updateTimeRange.bind(this))
            .then(this.issueQueries.bind(this))
            .catch(function (err) {
            _this.processDataError(err);
        });
    };
    MetricsPanelCtrl.prototype.processDataError = function (err) {
        var _this = this;
        // if canceled  keep loading set to true
        if (err.cancelled) {
            console.log('Panel request cancelled', err);
            return;
        }
        this.loading = false;
        this.error = err.message || 'Request Error';
        this.inspector = { error: err };
        if (err.data) {
            if (err.data.message) {
                this.error = err.data.message;
            }
            if (err.data.error) {
                this.error = err.data.error;
            }
        }
        console.log('Panel data error:', err);
        return this.$timeout(function () {
            _this.events.emit('data-error', err);
        });
    };
    MetricsPanelCtrl.prototype.updateTimeRange = function (datasource) {
        this.datasource = datasource || this.datasource;
        this.range = this.timeSrv.timeRange();
        this.resolution = Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_5__["getResolution"])(this.panel);
        var newTimeData = Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_5__["applyPanelTimeOverrides"])(this.panel, this.range);
        this.timeInfo = newTimeData.timeInfo;
        this.range = newTimeData.timeRange;
        this.calculateInterval();
        return this.datasource;
    };
    MetricsPanelCtrl.prototype.calculateInterval = function () {
        var intervalOverride = this.panel.interval;
        // if no panel interval check datasource
        if (intervalOverride) {
            intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
        }
        else if (this.datasource && this.datasource.interval) {
            intervalOverride = this.datasource.interval;
        }
        var res = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_2__["default"].calculateInterval(this.range, this.resolution, intervalOverride);
        this.interval = res.interval;
        this.intervalMs = res.intervalMs;
    };
    MetricsPanelCtrl.prototype.issueQueries = function (datasource) {
        this.datasource = datasource;
        var panel = this.panel;
        var queryRunner = panel.getQueryRunner();
        if (!this.querySubscription) {
            this.querySubscription = queryRunner.getData().subscribe(this.panelDataObserver);
        }
        return queryRunner.run({
            datasource: panel.datasource,
            queries: panel.targets,
            panelId: panel.id,
            dashboardId: this.dashboard.id,
            timezone: this.dashboard.timezone,
            timeRange: this.range,
            widthPixels: this.resolution,
            maxDataPoints: panel.maxDataPoints,
            minInterval: panel.interval,
            scopedVars: panel.scopedVars,
            cacheTimeout: panel.cacheTimeout,
            transformations: panel.transformations,
        });
    };
    MetricsPanelCtrl.prototype.handleDataFrames = function (data) {
        this.loading = false;
        if (this.dashboard && this.dashboard.snapshot) {
            this.panel.snapshotData = data.map(function (frame) { return Object(_grafana_data__WEBPACK_IMPORTED_MODULE_6__["toDataFrameDTO"])(frame); });
        }
        try {
            this.events.emit('data-frames-received', data);
        }
        catch (err) {
            this.processDataError(err);
        }
    };
    MetricsPanelCtrl.prototype.handleQueryResult = function (result) {
        this.loading = false;
        if (this.dashboard.snapshot) {
            this.panel.snapshotData = result.data;
        }
        if (!result || !result.data) {
            console.log('Data source query result invalid, missing data field:', result);
            result = { data: [] };
        }
        try {
            this.events.emit('data-received', result.data);
        }
        catch (err) {
            this.processDataError(err);
        }
    };
    MetricsPanelCtrl.prototype.getAdditionalMenuItems = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var items, _a, _b, _c;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
                switch (_d.label) {
                    case 0:
                        items = [];
                        if (!(this.contextSrv.hasAccessToExplore() && this.datasource)) return [3 /*break*/, 2];
                        _b = (_a = items).push;
                        _c = {
                            text: 'Explore',
                            icon: 'gicon gicon-explore',
                            shortcut: 'x'
                        };
                        return [4 /*yield*/, Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__["getExploreUrl"])(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv)];
                    case 1:
                        _b.apply(_a, [(_c.href = _d.sent(),
                                _c)]);
                        _d.label = 2;
                    case 2: return [2 /*return*/, items];
                }
            });
        });
    };
    return MetricsPanelCtrl;
}(app_features_panel_panel_ctrl__WEBPACK_IMPORTED_MODULE_3__["PanelCtrl"]));



/***/ }),

/***/ "./public/app/features/panel/panel_ctrl.ts":
/*!*************************************************!*\
  !*** ./public/app/features/panel/panel_ctrl.ts ***!
  \*************************************************/
/*! exports provided: PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return PanelCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_text__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/text */ "./public/app/core/utils/text.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var app_core_utils_factors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/utils/factors */ "./public/app/core/utils/factors.ts");
/* harmony import */ var app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/features/dashboard/utils/panel */ "./public/app/features/dashboard/utils/panel.ts");
/* harmony import */ var app_core_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/constants */ "./public/app/core/constants.ts");
/* harmony import */ var _panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./panellinks/linkSuppliers */ "./public/app/features/panel/panellinks/linkSuppliers.ts");










var PanelCtrl = /** @class */ (function () {
    function PanelCtrl($scope, $injector) {
        var _this = this;
        // overriden from react
        this.onPluginTypeChange = function (plugin) { };
        this.$injector = $injector;
        this.$location = $injector.get('$location');
        this.$scope = $scope;
        this.$timeout = $injector.get('$timeout');
        this.editorTabs = [];
        this.events = this.panel.events;
        this.timing = {}; // not used but here to not break plugins
        var plugin = app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].panels[this.panel.type];
        if (plugin) {
            this.pluginId = plugin.id;
            this.pluginName = plugin.name;
        }
        $scope.$on('component-did-mount', function () { return _this.panelDidMount(); });
    }
    PanelCtrl.prototype.panelDidMount = function () {
        this.events.emit('component-did-mount');
        this.dashboard.panelInitialized(this.panel);
    };
    PanelCtrl.prototype.renderingCompleted = function () {
        app_core_core__WEBPACK_IMPORTED_MODULE_5__["profiler"].renderingCompleted();
    };
    PanelCtrl.prototype.refresh = function () {
        this.panel.refresh();
    };
    PanelCtrl.prototype.publishAppEvent = function (evtName, evt) {
        this.$scope.$root.appEvent(evtName, evt);
    };
    PanelCtrl.prototype.changeView = function (fullscreen, edit) {
        this.publishAppEvent('panel-change-view', {
            fullscreen: fullscreen,
            edit: edit,
            panelId: this.panel.id,
        });
    };
    PanelCtrl.prototype.viewPanel = function () {
        this.changeView(true, false);
    };
    PanelCtrl.prototype.editPanel = function () {
        this.changeView(true, true);
    };
    PanelCtrl.prototype.exitFullscreen = function () {
        this.changeView(false, false);
    };
    PanelCtrl.prototype.initEditMode = function () {
        if (!this.editModeInitiated) {
            this.editModeInitiated = true;
            this.events.emit('init-edit-mode', null);
            this.maxPanelsPerRowOptions = Object(app_core_utils_factors__WEBPACK_IMPORTED_MODULE_6__["default"])(app_core_constants__WEBPACK_IMPORTED_MODULE_8__["GRID_COLUMN_COUNT"]);
        }
    };
    PanelCtrl.prototype.addEditorTab = function (title, directiveFn, index, icon) {
        var editorTab = { title: title, directiveFn: directiveFn, icon: icon };
        if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isString(directiveFn)) {
            editorTab.directiveFn = function () {
                return { templateUrl: directiveFn };
            };
        }
        if (index) {
            this.editorTabs.splice(index, 0, editorTab);
        }
        else {
            this.editorTabs.push(editorTab);
        }
    };
    PanelCtrl.prototype.getMenu = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var menu, _a, _b, _c, extendedMenu;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
                switch (_d.label) {
                    case 0:
                        menu = [];
                        menu.push({
                            text: 'View',
                            click: 'ctrl.viewPanel();',
                            icon: 'gicon gicon-viewer',
                            shortcut: 'v',
                        });
                        if (this.dashboard.meta.canEdit) {
                            menu.push({
                                text: 'Edit',
                                click: 'ctrl.editPanel();',
                                role: 'Editor',
                                icon: 'gicon gicon-editor',
                                shortcut: 'e',
                            });
                        }
                        menu.push({
                            text: 'Share',
                            click: 'ctrl.sharePanel();',
                            icon: 'fa fa-fw fa-share',
                            shortcut: 'p s',
                        });
                        _b = 
                        // Additional items from sub-class
                        (_a = menu.push).apply;
                        _c = [
                            // Additional items from sub-class
                            menu];
                        return [4 /*yield*/, this.getAdditionalMenuItems()];
                    case 1:
                        // Additional items from sub-class
                        _b.apply(_a, _c.concat([tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"].apply(void 0, [(_d.sent())])]));
                        extendedMenu = this.getExtendedMenu();
                        menu.push({
                            text: 'More ...',
                            click: '',
                            icon: 'fa fa-fw fa-cube',
                            submenu: extendedMenu,
                        });
                        if (this.dashboard.meta.canEdit) {
                            menu.push({ divider: true, role: 'Editor' });
                            menu.push({
                                text: 'Remove',
                                click: 'ctrl.removePanel();',
                                role: 'Editor',
                                icon: 'fa fa-fw fa-trash',
                                shortcut: 'p r',
                            });
                        }
                        return [2 /*return*/, menu];
                }
            });
        });
    };
    PanelCtrl.prototype.getExtendedMenu = function () {
        var menu = [];
        if (!this.panel.fullscreen && this.dashboard.meta.canEdit) {
            menu.push({
                text: 'Duplicate',
                click: 'ctrl.duplicate()',
                role: 'Editor',
                shortcut: 'p d',
            });
            menu.push({
                text: 'Copy',
                click: 'ctrl.copyPanel()',
                role: 'Editor',
            });
        }
        menu.push({
            text: 'Panel JSON',
            click: 'ctrl.editPanelJson(); dismiss();',
        });
        this.events.emit('init-panel-actions', menu);
        return menu;
    };
    // Override in sub-class to add items before extended menu
    PanelCtrl.prototype.getAdditionalMenuItems = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, Promise, function () {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                return [2 /*return*/, []];
            });
        });
    };
    PanelCtrl.prototype.otherPanelInFullscreenMode = function () {
        return this.dashboard.meta.fullscreen && !this.panel.fullscreen;
    };
    PanelCtrl.prototype.calculatePanelHeight = function (containerHeight) {
        this.containerHeight = containerHeight;
        this.height = Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__["calculateInnerPanelHeight"])(this.panel, containerHeight);
    };
    PanelCtrl.prototype.render = function (payload) {
        this.events.emit('render', payload);
    };
    PanelCtrl.prototype.duplicate = function () {
        Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__["duplicatePanel"])(this.dashboard, this.panel);
    };
    PanelCtrl.prototype.removePanel = function () {
        Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__["removePanel"])(this.dashboard, this.panel, true);
    };
    PanelCtrl.prototype.editPanelJson = function () {
        Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__["editPanelJson"])(this.dashboard, this.panel);
    };
    PanelCtrl.prototype.copyPanel = function () {
        Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__["copyPanel"])(this.panel);
    };
    PanelCtrl.prototype.sharePanel = function () {
        Object(app_features_dashboard_utils_panel__WEBPACK_IMPORTED_MODULE_7__["sharePanel"])(this.dashboard, this.panel);
    };
    PanelCtrl.prototype.getInfoMode = function () {
        if (this.error) {
            return 'error';
        }
        if (!!this.panel.description) {
            return 'info';
        }
        if (this.panel.links && this.panel.links.length) {
            return 'links';
        }
        return '';
    };
    PanelCtrl.prototype.getInfoContent = function (options) {
        var e_1, _a;
        var panel = this.panel;
        var markdown = panel.description || '';
        if (options.mode === 'tooltip') {
            markdown = this.error || panel.description || '';
        }
        var templateSrv = this.$injector.get('templateSrv');
        var interpolatedMarkdown = templateSrv.replace(markdown, panel.scopedVars);
        var html = '<div class="markdown-html panel-info-content">';
        var md = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["renderMarkdown"])(interpolatedMarkdown);
        html += app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].disableSanitizeHtml ? md : Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_2__["sanitize"])(md);
        if (panel.links && panel.links.length > 0) {
            var interpolatedLinks = Object(_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_9__["getPanelLinksSupplier"])(panel).getLinks();
            html += '<ul class="panel-info-corner-links">';
            try {
                for (var interpolatedLinks_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](interpolatedLinks), interpolatedLinks_1_1 = interpolatedLinks_1.next(); !interpolatedLinks_1_1.done; interpolatedLinks_1_1 = interpolatedLinks_1.next()) {
                    var link = interpolatedLinks_1_1.value;
                    html +=
                        '<li><a class="panel-menu-link" href="' +
                            Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_2__["escapeHtml"])(link.href) +
                            '" target="' +
                            Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_2__["escapeHtml"])(link.target) +
                            '">' +
                            Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_2__["escapeHtml"])(link.title) +
                            '</a></li>';
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (interpolatedLinks_1_1 && !interpolatedLinks_1_1.done && (_a = interpolatedLinks_1.return)) _a.call(interpolatedLinks_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            html += '</ul>';
        }
        html += '</div>';
        return html;
    };
    return PanelCtrl;
}());



/***/ }),

/***/ "./public/app/features/panel/panel_directive.ts":
/*!******************************************************!*\
  !*** ./public/app/features/panel/panel_directive.ts ***!
  \******************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tether-drop */ "./node_modules/tether-drop/dist/js/drop.js");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tether_drop__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var baron__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! baron */ "./node_modules/baron/src/core.js");
/* harmony import */ var baron__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(baron__WEBPACK_IMPORTED_MODULE_3__);


// @ts-ignore

// @ts-ignore

var module = angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives');
var panelTemplate = "\n  <div class=\"panel-container\" ng-class=\"{'panel-container--no-title': !ctrl.panel.title.length}\">\n      <div class=\"panel-header\" ng-class=\"{'grid-drag-handle': !ctrl.panel.fullscreen}\">\n        <span class=\"panel-info-corner\">\n          <i class=\"fa\"></i>\n          <span class=\"panel-info-corner-inner\"></span>\n        </span>\n\n        <span class=\"panel-loading\" ng-show=\"ctrl.loading\">\n          <i class=\"fa fa-spinner fa-spin\"></i>\n        </span>\n\n        <panel-header class=\"panel-title-container\" panel-ctrl=\"ctrl\" aria-label=\"Panel Title\"></panel-header>\n      </div>\n\n      <div class=\"panel-content\">\n        <ng-transclude class=\"panel-height-helper\"></ng-transclude>\n      </div>\n    </div>\n  </div>\n";
module.directive('grafanaPanel', function ($rootScope, $document, $timeout) {
    return {
        restrict: 'E',
        template: panelTemplate,
        transclude: true,
        scope: { ctrl: '=' },
        link: function (scope, elem) {
            var panelContainer = elem.find('.panel-container');
            var panelContent = elem.find('.panel-content');
            var cornerInfoElem = elem.find('.panel-info-corner');
            var ctrl = scope.ctrl;
            var infoDrop;
            var panelScrollbar;
            // the reason for handling these classes this way is for performance
            // limit the watchers on panels etc
            var transparentLastState = false;
            var lastHasAlertRule = false;
            var lastAlertState;
            var hasAlertRule;
            function mouseEnter() {
                panelContainer.toggleClass('panel-hover-highlight', true);
                ctrl.dashboard.setPanelFocus(ctrl.panel.id);
            }
            function mouseLeave() {
                panelContainer.toggleClass('panel-hover-highlight', false);
                ctrl.dashboard.setPanelFocus(0);
            }
            function resizeScrollableContent() {
                if (panelScrollbar) {
                    panelScrollbar.update();
                }
            }
            // set initial transparency
            if (ctrl.panel.transparent) {
                transparentLastState = true;
                panelContainer.addClass('panel-transparent');
            }
            // update scrollbar after mounting
            ctrl.events.on('component-did-mount', function () {
                if (ctrl.__proto__.constructor.scrollable) {
                    var scrollRootClass = 'baron baron__root baron__clipper panel-content--scrollable';
                    var scrollerClass = 'baron__scroller';
                    var scrollBarHTML = "\n            <div class=\"baron__track\">\n              <div class=\"baron__bar\"></div>\n            </div>\n          ";
                    var scrollRoot = panelContent;
                    var scroller = panelContent.find(':first').find(':first');
                    scrollRoot.addClass(scrollRootClass);
                    jquery__WEBPACK_IMPORTED_MODULE_1___default()(scrollBarHTML).appendTo(scrollRoot);
                    scroller.addClass(scrollerClass);
                    panelScrollbar = baron__WEBPACK_IMPORTED_MODULE_3___default()({
                        root: scrollRoot[0],
                        scroller: scroller[0],
                        bar: '.baron__bar',
                        barOnCls: '_scrollbar',
                        scrollingCls: '_scrolling',
                    });
                    panelScrollbar.scroll();
                }
            });
            ctrl.events.on('panel-size-changed', function () {
                ctrl.calculatePanelHeight(panelContainer[0].offsetHeight);
                $timeout(function () {
                    resizeScrollableContent();
                    ctrl.render();
                });
            });
            ctrl.events.on('view-mode-changed', function () {
                // first wait one pass for dashboard fullscreen view mode to take effect (classses being applied)
                setTimeout(function () {
                    // then recalc style
                    ctrl.calculatePanelHeight(panelContainer[0].offsetHeight);
                    // then wait another cycle (this might not be needed)
                    $timeout(function () {
                        ctrl.render();
                        resizeScrollableContent();
                    });
                }, 10);
            });
            ctrl.events.on('render', function () {
                // set initial height
                if (!ctrl.height) {
                    ctrl.calculatePanelHeight(panelContainer[0].offsetHeight);
                }
                if (transparentLastState !== ctrl.panel.transparent) {
                    panelContainer.toggleClass('panel-transparent', ctrl.panel.transparent === true);
                    transparentLastState = ctrl.panel.transparent;
                }
                hasAlertRule = ctrl.panel.alert !== undefined;
                if (lastHasAlertRule !== hasAlertRule) {
                    panelContainer.toggleClass('panel-has-alert', hasAlertRule);
                    lastHasAlertRule = hasAlertRule;
                }
                if (ctrl.alertState) {
                    if (lastAlertState) {
                        panelContainer.removeClass('panel-alert-state--' + lastAlertState);
                    }
                    if (ctrl.alertState.state === 'ok' ||
                        ctrl.alertState.state === 'alerting' ||
                        ctrl.alertState.state === 'pending') {
                        panelContainer.addClass('panel-alert-state--' + ctrl.alertState.state);
                    }
                    lastAlertState = ctrl.alertState.state;
                }
                else if (lastAlertState) {
                    panelContainer.removeClass('panel-alert-state--' + lastAlertState);
                    lastAlertState = null;
                }
            });
            function updatePanelCornerInfo() {
                var cornerMode = ctrl.getInfoMode();
                cornerInfoElem[0].className = 'panel-info-corner panel-info-corner--' + cornerMode;
                if (cornerMode) {
                    if (infoDrop) {
                        infoDrop.destroy();
                    }
                    infoDrop = new tether_drop__WEBPACK_IMPORTED_MODULE_2___default.a({
                        target: cornerInfoElem[0],
                        content: function () {
                            return ctrl.getInfoContent({ mode: 'tooltip' });
                        },
                        classes: ctrl.error ? 'drop-error' : 'drop-help',
                        openOn: 'hover',
                        hoverOpenDelay: 100,
                        tetherOptions: {
                            attachment: 'bottom left',
                            targetAttachment: 'top left',
                            constraints: [
                                {
                                    to: 'window',
                                    attachment: 'together',
                                    pin: true,
                                },
                            ],
                        },
                    });
                }
            }
            scope.$watchGroup(['ctrl.error', 'ctrl.panel.description'], updatePanelCornerInfo);
            scope.$watchCollection('ctrl.panel.links', updatePanelCornerInfo);
            elem.on('mouseenter', mouseEnter);
            elem.on('mouseleave', mouseLeave);
            scope.$on('$destroy', function () {
                elem.off();
                cornerInfoElem.off();
                if (infoDrop) {
                    infoDrop.destroy();
                }
                if (panelScrollbar) {
                    panelScrollbar.dispose();
                }
            });
        },
    };
});
module.directive('panelHelpCorner', function ($rootScope) {
    return {
        restrict: 'E',
        template: "\n    <span class=\"alert-error panel-error small pointer\" ng-if=\"ctrl.error\" ng-click=\"ctrl.openInspector()\">\n    <span data-placement=\"top\" bs-tooltip=\"ctrl.error\">\n    <i class=\"fa fa-exclamation\"></i><span class=\"panel-error-arrow\"></span>\n    </span>\n    </span>\n    ",
        link: function (scope, elem) { },
    };
});


/***/ }),

/***/ "./public/app/features/panel/panel_editor_tab.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/panel/panel_editor_tab.ts ***!
  \*******************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);

var directiveModule = angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives');
var directiveCache = {};
/** @ngInject */
function panelEditorTab(dynamicDirectiveSrv) {
    return dynamicDirectiveSrv.create({
        scope: {
            ctrl: '=',
            editorTab: '=',
        },
        directive: function (scope) {
            var pluginId = scope.ctrl.pluginId;
            var tabName = scope.editorTab.title
                .toLowerCase()
                .replace(' ', '-')
                .replace('&', '')
                .replace(' ', '')
                .replace(' ', '-');
            if (directiveCache[pluginId]) {
                if (directiveCache[pluginId][tabName]) {
                    return directiveCache[pluginId][tabName];
                }
            }
            else {
                directiveCache[pluginId] = [];
            }
            var result = {
                fn: function () { return scope.editorTab.directiveFn(); },
                name: "panel-editor-tab-" + pluginId + tabName,
            };
            directiveCache[pluginId][tabName] = result;
            return result;
        },
    });
}
directiveModule.directive('panelEditorTab', panelEditorTab);


/***/ }),

/***/ "./public/app/features/panel/panel_header.ts":
/*!***************************************************!*\
  !*** ./public/app/features/panel/panel_header.ts ***!
  \***************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");


var template = "\n<span class=\"panel-title\">\n  <span class=\"icon-gf panel-alert-icon\"></span>\n  <span class=\"panel-title-text\">{{ctrl.panel.title | interpolateTemplateVars:this}}</span>\n  <span class=\"panel-menu-container dropdown\">\n    <span class=\"fa fa-caret-down panel-menu-toggle\" data-toggle=\"dropdown\"></span>\n    <ul class=\"dropdown-menu dropdown-menu--menu panel-menu\" role=\"menu\">\n    </ul>\n  </span>\n  <span class=\"panel-time-info\" ng-if=\"ctrl.timeInfo\"><i class=\"fa fa-clock-o\"></i> {{ctrl.timeInfo}}</span>\n</span>";
function renderMenuItem(item, ctrl) {
    var e_1, _a;
    var html = '';
    var listItemClass = '';
    if (item.divider) {
        return '<li class="divider"></li>';
    }
    if (item.submenu) {
        listItemClass = 'dropdown-submenu';
    }
    html += "<li class=\"" + listItemClass + "\"><a ";
    if (item.click) {
        html += " ng-click=\"" + item.click + "\"";
    }
    if (item.href) {
        html += " href=\"" + item.href + "\"";
    }
    html += "><i class=\"" + item.icon + "\"></i>";
    html += "<span class=\"dropdown-item-text\" aria-label=\"" + item.text + " panel menu item\">" + item.text + "</span>";
    if (item.shortcut) {
        html += "<span class=\"dropdown-menu-item-shortcut\">" + item.shortcut + "</span>";
    }
    html += "</a>";
    if (item.submenu) {
        html += '<ul class="dropdown-menu dropdown-menu--menu panel-menu">';
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](item.submenu), _c = _b.next(); !_c.done; _c = _b.next()) {
                var subitem = _c.value;
                html += renderMenuItem(subitem, ctrl);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        html += '</ul>';
    }
    html += "</li>";
    return html;
}
function createMenuTemplate(ctrl) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
        var html, _a, _b, item, e_2_1;
        var e_2, _c;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_d) {
            switch (_d.label) {
                case 0:
                    html = '';
                    _d.label = 1;
                case 1:
                    _d.trys.push([1, 6, 7, 8]);
                    return [4 /*yield*/, ctrl.getMenu()];
                case 2:
                    _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"].apply(void 0, [_d.sent()]), _b = _a.next();
                    _d.label = 3;
                case 3:
                    if (!!_b.done) return [3 /*break*/, 5];
                    item = _b.value;
                    html += renderMenuItem(item, ctrl);
                    _d.label = 4;
                case 4:
                    _b = _a.next();
                    return [3 /*break*/, 3];
                case 5: return [3 /*break*/, 8];
                case 6:
                    e_2_1 = _d.sent();
                    e_2 = { error: e_2_1 };
                    return [3 /*break*/, 8];
                case 7:
                    try {
                        if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
                    }
                    finally { if (e_2) throw e_2.error; }
                    return [7 /*endfinally*/];
                case 8: return [2 /*return*/, html];
            }
        });
    });
}
/** @ngInject */
function panelHeader($compile) {
    var _this = this;
    return {
        restrict: 'E',
        template: template,
        link: function (scope, elem, attrs) {
            var menuElem = elem.find('.panel-menu');
            var menuScope;
            var isDragged;
            elem.click(function (evt) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
                var targetClass, menuHtml;
                return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            targetClass = evt.target.className;
                            // remove existing scope
                            if (menuScope) {
                                menuScope.$destroy();
                            }
                            menuScope = scope.$new();
                            return [4 /*yield*/, createMenuTemplate(scope.ctrl)];
                        case 1:
                            menuHtml = _a.sent();
                            menuElem.html(menuHtml);
                            $compile(menuElem)(menuScope);
                            if (targetClass.indexOf('panel-title-text') >= 0 || targetClass.indexOf('panel-title') >= 0) {
                                togglePanelMenu(evt);
                            }
                            return [2 /*return*/];
                    }
                });
            }); });
            function togglePanelMenu(e) {
                if (!isDragged) {
                    e.stopPropagation();
                    elem.find('[data-toggle=dropdown]').dropdown('toggle');
                }
            }
            var mouseX, mouseY;
            elem.mousedown(function (e) {
                mouseX = e.pageX;
                mouseY = e.pageY;
            });
            elem.mouseup(function (e) {
                if (mouseX === e.pageX && mouseY === e.pageY) {
                    isDragged = false;
                }
                else {
                    isDragged = true;
                }
            });
        },
    };
}
app_core_core__WEBPACK_IMPORTED_MODULE_1__["coreModule"].directive('panelHeader', panelHeader);


/***/ }),

/***/ "./public/app/features/panel/panellinks/linkSuppliers.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/panel/panellinks/linkSuppliers.ts ***!
  \***************************************************************/
/*! exports provided: getFieldLinksSupplier, getPanelLinksSupplier */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFieldLinksSupplier", function() { return getFieldLinksSupplier; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelLinksSupplier", function() { return getPanelLinksSupplier; });
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _link_srv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");


/**
 * Link suppliers creates link models based on a link origin
 */
var getFieldLinksSupplier = function (value) {
    var links = value.field.links;
    if (!links || links.length === 0) {
        return undefined;
    }
    return {
        getLinks: function (_scopedVars) {
            var scopedVars = {};
            if (value.view) {
                var dataFrame = value.view.dataFrame;
                scopedVars['__series'] = {
                    value: {
                        name: dataFrame.name,
                        labels: dataFrame.labels,
                        refId: dataFrame.refId,
                    },
                    text: 'Series',
                };
                var field = value.colIndex !== undefined ? dataFrame.fields[value.colIndex] : undefined;
                if (field) {
                    console.log('Full Field Info:', field);
                    scopedVars['__field'] = {
                        value: {
                            name: field.name,
                        },
                        text: 'Field',
                    };
                }
                if (value.rowIndex) {
                    var timeField = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_0__["getTimeField"])(dataFrame).timeField;
                    scopedVars['__value'] = {
                        value: {
                            raw: field.values.get(value.rowIndex),
                            numeric: value.display.numeric,
                            text: value.display.text,
                            time: timeField ? timeField.values.get(value.rowIndex) : undefined,
                        },
                        text: 'Value',
                    };
                }
                else {
                    // calculation
                    scopedVars['__value'] = {
                        value: {
                            raw: value.display.numeric,
                            numeric: value.display.numeric,
                            text: value.display.text,
                            calc: value.name,
                        },
                        text: 'Value',
                    };
                }
            }
            else {
                console.log('VALUE', value);
            }
            return links.map(function (link) {
                return Object(_link_srv__WEBPACK_IMPORTED_MODULE_1__["getLinkSrv"])().getDataLinkUIModel(link, scopedVars, value);
            });
        },
    };
};
var getPanelLinksSupplier = function (value) {
    var links = value.links;
    if (!links || links.length === 0) {
        return undefined;
    }
    return {
        getLinks: function () {
            return links.map(function (link) {
                return Object(_link_srv__WEBPACK_IMPORTED_MODULE_1__["getLinkSrv"])().getDataLinkUIModel(link, value.scopedVars, value);
            });
        },
    };
};


/***/ }),

/***/ "./public/app/features/panel/panellinks/link_srv.ts":
/*!**********************************************************!*\
  !*** ./public/app/features/panel/panellinks/link_srv.ts ***!
  \**********************************************************/
/*! exports provided: getPanelLinksVariableSuggestions, getDataLinksVariableSuggestions, getCalculationValueDataLinksVariableSuggestions, LinkSrv, setLinkSrv, getLinkSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPanelLinksVariableSuggestions", function() { return getPanelLinksVariableSuggestions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataLinksVariableSuggestions", function() { return getDataLinksVariableSuggestions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCalculationValueDataLinksVariableSuggestions", function() { return getCalculationValueDataLinksVariableSuggestions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinkSrv", function() { return LinkSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setLinkSrv", function() { return setLinkSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLinkSrv", function() { return getLinkSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/features/templating/template_srv */ "./public/app/features/templating/template_srv.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/url */ "./public/app/core/utils/url.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");







var timeRangeVars = [
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].keepTime,
        label: 'Time range',
        documentation: 'Adds current time range',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].BuiltIn,
    },
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].timeRangeFrom,
        label: 'Time range: from',
        documentation: "Adds current time range's from value",
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].BuiltIn,
    },
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].timeRangeTo,
        label: 'Time range: to',
        documentation: "Adds current time range's to value",
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].BuiltIn,
    },
];
var fieldVars = [
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].fieldName,
        label: 'Name',
        documentation: 'Field name of the clicked datapoint (in ms epoch)',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Field,
    },
];
var valueVars = [
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].valueNumeric,
        label: 'Numeric',
        documentation: 'Numeric representation of selected value',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Value,
    },
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].valueText,
        label: 'Text',
        documentation: 'Text representation of selected value',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Value,
    },
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].valueRaw,
        label: 'Raw',
        documentation: 'Raw value',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Value,
    },
];
var buildLabelPath = function (label) {
    return label.indexOf('.') > -1 ? "[\"" + label + "\"]" : "." + label;
};
var getPanelLinksVariableSuggestions = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](app_features_templating_template_srv__WEBPACK_IMPORTED_MODULE_2__["default"].variables.map(function (variable) { return ({
    value: variable.name,
    label: variable.name,
    origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Template,
}); }), [
    {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].includeVars,
        label: 'All variables',
        documentation: 'Adds current variables',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Template,
    }
], timeRangeVars); };
var getSeriesVars = function (dataFrames) {
    var labels = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.chain(dataFrames.map(function (df) { return Object.keys(df.labels || {}); }))
        .flatten()
        .uniq()
        .value();
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([
        {
            value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].seriesName,
            label: 'Name',
            documentation: 'Name of the series',
            origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Series,
        }
    ], labels.map(function (label) { return ({
        value: "__series.labels" + buildLabelPath(label),
        label: "labels." + label,
        documentation: label + " label value",
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Series,
    }); }));
};
var getDataLinksVariableSuggestions = function (dataFrames) {
    var seriesVars = getSeriesVars(dataFrames);
    var valueTimeVar = {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].valueTime,
        label: 'Time',
        documentation: 'Time value of the clicked datapoint (in ms epoch)',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Value,
    };
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](seriesVars, fieldVars, valueVars, [valueTimeVar], getPanelLinksVariableSuggestions());
};
var getCalculationValueDataLinksVariableSuggestions = function (dataFrames) {
    var seriesVars = getSeriesVars(dataFrames);
    var valueCalcVar = {
        value: "" + _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].valueCalc,
        label: 'Calculation name',
        documentation: 'Name of the calculation the value is a result of',
        origin: _grafana_ui__WEBPACK_IMPORTED_MODULE_5__["VariableOrigin"].Value,
    };
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](seriesVars, fieldVars, valueVars, [valueCalcVar], getPanelLinksVariableSuggestions());
};
var LinkSrv = /** @class */ (function () {
    /** @ngInject */
    function LinkSrv(templateSrv, timeSrv) {
        var _this = this;
        this.templateSrv = templateSrv;
        this.timeSrv = timeSrv;
        this.getDataLinkUIModel = function (link, scopedVars, origin) {
            var _a;
            var params = {};
            var timeRangeUrl = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__["toUrlParams"])(_this.timeSrv.timeRangeForUrl());
            var info = {
                href: link.url.replace(/\s|\n/g, ''),
                title: _this.templateSrv.replace(link.title || '', scopedVars),
                target: link.targetBlank ? '_blank' : '_self',
                origin: origin,
            };
            _this.templateSrv.fillVariableValuesForUrl(params, scopedVars);
            var variablesQuery = Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__["toUrlParams"])(params);
            info.href = _this.templateSrv.replace(info.href, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, scopedVars, (_a = {}, _a[_grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].keepTime] = {
                text: timeRangeUrl,
                value: timeRangeUrl,
            }, _a[_grafana_ui__WEBPACK_IMPORTED_MODULE_5__["DataLinkBuiltInVars"].includeVars] = {
                text: variablesQuery,
                value: variablesQuery,
            }, _a)));
            return info;
        };
    }
    LinkSrv.prototype.getLinkUrl = function (link) {
        var url = this.templateSrv.replace(link.url || '');
        var params = {};
        if (link.keepTime) {
            var range = this.timeSrv.timeRangeForUrl();
            params['from'] = range.from;
            params['to'] = range.to;
        }
        if (link.includeVars) {
            this.templateSrv.fillVariableValuesForUrl(params);
        }
        return Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__["appendQueryToUrl"])(url, Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_4__["toUrlParams"])(params));
    };
    LinkSrv.prototype.getAnchorInfo = function (link) {
        var info = {};
        info.href = this.getLinkUrl(link);
        info.title = this.templateSrv.replace(link.title || '');
        return info;
    };
    /**
     * getPanelLinkAnchorInfo method is left for plugins compatibility reasons
     *
     * @deprecated Drilldown links should be generated using getDataLinkUIModel method
     */
    LinkSrv.prototype.getPanelLinkAnchorInfo = function (link, scopedVars) {
        Object(_grafana_data__WEBPACK_IMPORTED_MODULE_6__["deprecationWarning"])('link_srv.ts', 'getPanelLinkAnchorInfo', 'getDataLinkUIModel');
        return this.getDataLinkUIModel(link, scopedVars, {});
    };
    return LinkSrv;
}());

var singleton;
function setLinkSrv(srv) {
    singleton = srv;
}
function getLinkSrv() {
    return singleton;
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_3__["default"].service('linkSrv', LinkSrv);


/***/ }),

/***/ "./public/app/features/panel/panellinks/module.ts":
/*!********************************************************!*\
  !*** ./public/app/features/panel/panellinks/module.ts ***!
  \********************************************************/
/*! exports provided: PanelLinksEditorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelLinksEditorCtrl", function() { return PanelLinksEditorCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _link_srv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");



function panelLinksEditor() {
    return {
        scope: {
            panel: '=',
        },
        restrict: 'E',
        controller: 'PanelLinksEditorCtrl',
        templateUrl: 'public/app/features/panel/panellinks/module.html',
        link: function () { },
    };
}
var PanelLinksEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function PanelLinksEditorCtrl($scope, backendSrv) {
        $scope.panel.links = $scope.panel.links || [];
        $scope.addLink = function () {
            $scope.panel.links.push({
                type: 'dashboard',
            });
        };
        $scope.searchDashboards = function (queryStr, callback) {
            backendSrv.search({ query: queryStr }).then(function (hits) {
                var dashboards = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(hits, function (dash) {
                    return dash.title;
                });
                callback(dashboards);
            });
        };
        $scope.dashboardChanged = function (link) {
            backendSrv.search({ query: link.dashboard }).then(function (hits) {
                var dashboard = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(hits, { title: link.dashboard });
                if (dashboard) {
                    if (dashboard.url) {
                        link.url = dashboard.url;
                    }
                    else {
                        // To support legacy url's
                        link.dashUri = dashboard.uri;
                    }
                    link.title = dashboard.title;
                }
            });
        };
        $scope.deleteLink = function (link) {
            $scope.panel.links = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.without($scope.panel.links, link);
        };
    }
    return PanelLinksEditorCtrl;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a
    .module('grafana.directives')
    .directive('panelLinksEditor', panelLinksEditor)
    .controller('PanelLinksEditorCtrl', PanelLinksEditorCtrl);


/***/ }),

/***/ "./public/app/features/panel/query_ctrl.ts":
/*!*************************************************!*\
  !*** ./public/app/features/panel/query_ctrl.ts ***!
  \*************************************************/
/*! exports provided: QueryCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryCtrl", function() { return QueryCtrl; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

var QueryCtrl = /** @class */ (function () {
    function QueryCtrl($scope, $injector) {
        this.$scope = $scope;
        this.$injector = $injector;
        this.panel = this.panelCtrl.panel;
        this.isLastQuery = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.indexOf(this.panel.targets, this.target) === this.panel.targets.length - 1;
    }
    QueryCtrl.prototype.refresh = function () {
        this.panelCtrl.refresh();
    };
    return QueryCtrl;
}());



/***/ }),

/***/ "./public/app/features/panel/query_editor_row.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/panel/query_editor_row.ts ***!
  \*******************************************************/
/*! exports provided: QueryRowCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryRowCtrl", function() { return QueryRowCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);

var module = angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.directives');
var QueryRowCtrl = /** @class */ (function () {
    function QueryRowCtrl() {
        this.panelCtrl = this.queryCtrl.panelCtrl;
        this.target = this.queryCtrl.target;
        this.panel = this.panelCtrl.panel;
        if (this.hasTextEditMode && this.queryCtrl.toggleEditorMode) {
            // expose this function to react parent component
            this.panelCtrl.toggleEditorMode = this.queryCtrl.toggleEditorMode.bind(this.queryCtrl);
        }
        if (this.queryCtrl.getCollapsedText) {
            // expose this function to react parent component
            this.panelCtrl.getCollapsedText = this.queryCtrl.getCollapsedText.bind(this.queryCtrl);
        }
    }
    return QueryRowCtrl;
}());

/** @ngInject */
function queryEditorRowDirective() {
    return {
        restrict: 'E',
        controller: QueryRowCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        templateUrl: 'public/app/features/panel/partials/query_editor_row.html',
        transclude: true,
        scope: {
            queryCtrl: '=',
            canCollapse: '=',
            hasTextEditMode: '=',
        },
    };
}
module.directive('queryEditorRow', queryEditorRowDirective);


/***/ }),

/***/ "./public/app/features/panel/repeat_option.ts":
/*!****************************************************!*\
  !*** ./public/app/features/panel/repeat_option.ts ***!
  \****************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");

var template = "\n<div class=\"gf-form-select-wrapper max-width-18\">\n  <select class=\"gf-form-input\" ng-model=\"panel.repeat\" ng-options=\"f.value as f.text for f in variables\" ng-change=\"optionChanged()\">\n  <option value=\"\"></option>\n</div>\n";
/** @ngInject */
function dashRepeatOptionDirective(variableSrv) {
    return {
        restrict: 'E',
        template: template,
        scope: {
            panel: '=',
        },
        link: function (scope, element) {
            element.css({ display: 'block', width: '100%' });
            scope.variables = variableSrv.variables.map(function (item) {
                return { text: item.name, value: item.name };
            });
            if (scope.variables.length === 0) {
                scope.variables.unshift({
                    text: 'No template variables found',
                    value: null,
                });
            }
            scope.variables.unshift({ text: 'Disabled', value: null });
            // if repeat is set and no direction set to horizontal
            if (scope.panel.repeat && !scope.panel.repeatDirection) {
                scope.panel.repeatDirection = 'h';
            }
            scope.optionChanged = function () {
                if (scope.panel.repeat) {
                    scope.panel.repeatDirection = 'h';
                }
            };
        },
    };
}
app_core_core__WEBPACK_IMPORTED_MODULE_0__["coreModule"].directive('dashRepeatOption', dashRepeatOptionDirective);


/***/ }),

/***/ "./public/app/features/playlist/all.ts":
/*!*********************************************!*\
  !*** ./public/app/features/playlist/all.ts ***!
  \*********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _playlists_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./playlists_ctrl */ "./public/app/features/playlist/playlists_ctrl.ts");
/* harmony import */ var _playlist_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./playlist_search */ "./public/app/features/playlist/playlist_search.ts");
/* harmony import */ var _playlist_srv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./playlist_srv */ "./public/app/features/playlist/playlist_srv.ts");
/* harmony import */ var _playlist_edit_ctrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./playlist_edit_ctrl */ "./public/app/features/playlist/playlist_edit_ctrl.ts");
/* harmony import */ var _playlist_routes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./playlist_routes */ "./public/app/features/playlist/playlist_routes.ts");







/***/ }),

/***/ "./public/app/features/playlist/playlist_edit_ctrl.ts":
/*!************************************************************!*\
  !*** ./public/app/features/playlist/playlist_edit_ctrl.ts ***!
  \************************************************************/
/*! exports provided: PlaylistEditCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistEditCtrl", function() { return PlaylistEditCtrl; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../core/core_module */ "./public/app/core/core_module.ts");


var PlaylistEditCtrl = /** @class */ (function () {
    /** @ngInject */
    function PlaylistEditCtrl($scope, backendSrv, $location, $route, navModelSrv) {
        var _this = this;
        this.$scope = $scope;
        this.backendSrv = backendSrv;
        this.$location = $location;
        this.filteredDashboards = [];
        this.filteredTags = [];
        this.searchQuery = '';
        this.loading = false;
        this.playlist = {
            interval: '5m',
        };
        this.playlistItems = [];
        this.dashboardresult = [];
        this.tagresult = [];
        this.navModel = navModelSrv.getNav('dashboards', 'playlists', 0);
        this.isNew = !$route.current.params.id;
        if ($route.current.params.id) {
            var playlistId = $route.current.params.id;
            backendSrv.get('/api/playlists/' + playlistId).then(function (result) {
                _this.playlist = result;
            });
            backendSrv.get('/api/playlists/' + playlistId + '/items').then(function (result) {
                _this.playlistItems = result;
            });
        }
    }
    PlaylistEditCtrl.prototype.filterFoundPlaylistItems = function () {
        var _this = this;
        this.filteredDashboards = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.reject(this.dashboardresult, function (playlistItem) {
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(_this.playlistItems, function (listPlaylistItem) {
                return parseInt(listPlaylistItem.value, 10) === playlistItem.id;
            });
        });
        this.filteredTags = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.reject(this.tagresult, function (tag) {
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(_this.playlistItems, function (listPlaylistItem) {
                return listPlaylistItem.value === tag.term;
            });
        });
    };
    PlaylistEditCtrl.prototype.addPlaylistItem = function (playlistItem) {
        playlistItem.value = playlistItem.id.toString();
        playlistItem.type = 'dashboard_by_id';
        playlistItem.order = this.playlistItems.length + 1;
        this.playlistItems.push(playlistItem);
        this.filterFoundPlaylistItems();
    };
    PlaylistEditCtrl.prototype.addTagPlaylistItem = function (tag) {
        var playlistItem = {
            value: tag.term,
            type: 'dashboard_by_tag',
            order: this.playlistItems.length + 1,
            title: tag.term,
        };
        this.playlistItems.push(playlistItem);
        this.filterFoundPlaylistItems();
    };
    PlaylistEditCtrl.prototype.removePlaylistItem = function (playlistItem) {
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.remove(this.playlistItems, function (listedPlaylistItem) {
            return playlistItem === listedPlaylistItem;
        });
        this.filterFoundPlaylistItems();
    };
    PlaylistEditCtrl.prototype.savePlaylist = function (playlist, playlistItems) {
        var _this = this;
        var savePromise;
        playlist.items = playlistItems;
        savePromise = playlist.id
            ? this.backendSrv.put('/api/playlists/' + playlist.id, playlist)
            : this.backendSrv.post('/api/playlists', playlist);
        savePromise.then(function () {
            _this.$scope.appEvent('alert-success', ['Playlist saved', '']);
            _this.$location.path('/playlists');
        }, function () {
            _this.$scope.appEvent('alert-error', ['Unable to save playlist', '']);
        });
    };
    PlaylistEditCtrl.prototype.isPlaylistEmpty = function () {
        return !this.playlistItems.length;
    };
    PlaylistEditCtrl.prototype.backToList = function () {
        this.$location.path('/playlists');
    };
    PlaylistEditCtrl.prototype.searchStarted = function (promise) {
        var _this = this;
        promise.then(function (data) {
            _this.dashboardresult = data.dashboardResult;
            _this.tagresult = data.tagResult;
            _this.filterFoundPlaylistItems();
        });
    };
    PlaylistEditCtrl.prototype.movePlaylistItem = function (playlistItem, offset) {
        var currentPosition = this.playlistItems.indexOf(playlistItem);
        var newPosition = currentPosition + offset;
        if (newPosition >= 0 && newPosition < this.playlistItems.length) {
            this.playlistItems.splice(currentPosition, 1);
            this.playlistItems.splice(newPosition, 0, playlistItem);
        }
    };
    PlaylistEditCtrl.prototype.movePlaylistItemUp = function (playlistItem) {
        this.movePlaylistItem(playlistItem, -1);
    };
    PlaylistEditCtrl.prototype.movePlaylistItemDown = function (playlistItem) {
        this.movePlaylistItem(playlistItem, 1);
    };
    return PlaylistEditCtrl;
}());

_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].controller('PlaylistEditCtrl', PlaylistEditCtrl);


/***/ }),

/***/ "./public/app/features/playlist/playlist_routes.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/playlist/playlist_routes.ts ***!
  \*********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);

/** @ngInject */
function grafanaRoutes($routeProvider) {
    $routeProvider
        .when('/playlists', {
        templateUrl: 'public/app/features/playlist/partials/playlists.html',
        controllerAs: 'ctrl',
        controller: 'PlaylistsCtrl',
    })
        .when('/playlists/create', {
        templateUrl: 'public/app/features/playlist/partials/playlist.html',
        controllerAs: 'ctrl',
        controller: 'PlaylistEditCtrl',
    })
        .when('/playlists/edit/:id', {
        templateUrl: 'public/app/features/playlist/partials/playlist.html',
        controllerAs: 'ctrl',
        controller: 'PlaylistEditCtrl',
    })
        .when('/playlists/play/:id', {
        template: '',
        resolve: {
            init: function (playlistSrv, $route) {
                var playlistId = $route.current.params.id;
                playlistSrv.start(playlistId);
            },
        },
    });
}
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.routes').config(grafanaRoutes);


/***/ }),

/***/ "./public/app/features/playlist/playlist_search.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/playlist/playlist_search.ts ***!
  \*********************************************************/
/*! exports provided: PlaylistSearchCtrl, playlistSearchDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistSearchCtrl", function() { return PlaylistSearchCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "playlistSearchDirective", function() { return playlistSearchDirective; });
/* harmony import */ var _core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../core/core_module */ "./public/app/core/core_module.ts");

var PlaylistSearchCtrl = /** @class */ (function () {
    /** @ngInject */
    function PlaylistSearchCtrl($timeout, backendSrv) {
        var _this = this;
        this.backendSrv = backendSrv;
        this.query = { query: '', tag: [], starred: false, limit: 20 };
        $timeout(function () {
            _this.query.query = '';
            _this.query.type = 'dash-db';
            _this.searchDashboards();
        }, 100);
    }
    PlaylistSearchCtrl.prototype.searchDashboards = function () {
        this.tagsMode = false;
        var prom = {};
        prom.promise = this.backendSrv.search(this.query).then(function (result) {
            return {
                dashboardResult: result,
                tagResult: [],
            };
        });
        this.searchStarted(prom);
    };
    PlaylistSearchCtrl.prototype.showStarred = function () {
        this.query.starred = !this.query.starred;
        this.searchDashboards();
    };
    PlaylistSearchCtrl.prototype.queryHasNoFilters = function () {
        return this.query.query === '' && this.query.starred === false && this.query.tag.length === 0;
    };
    PlaylistSearchCtrl.prototype.filterByTag = function (tag, evt) {
        this.query.tag.push(tag);
        this.searchDashboards();
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };
    PlaylistSearchCtrl.prototype.getTags = function () {
        var prom = {};
        prom.promise = this.backendSrv.get('/api/dashboards/tags').then(function (result) {
            return {
                dashboardResult: [],
                tagResult: result,
            };
        });
        this.searchStarted(prom);
    };
    return PlaylistSearchCtrl;
}());

function playlistSearchDirective() {
    return {
        restrict: 'E',
        templateUrl: 'public/app/features/playlist/partials/playlist_search.html',
        controller: PlaylistSearchCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            searchStarted: '&',
        },
    };
}
_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('playlistSearch', playlistSearchDirective);


/***/ }),

/***/ "./public/app/features/playlist/playlist_srv.ts":
/*!******************************************************!*\
  !*** ./public/app/features/playlist/playlist_srv.ts ***!
  \******************************************************/
/*! exports provided: queryParamsToPreserve, PlaylistSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queryParamsToPreserve", function() { return queryParamsToPreserve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistSrv", function() { return PlaylistSrv; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/url */ "./public/app/core/utils/url.ts");
/* harmony import */ var _core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_store_store__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/store/store */ "./public/app/store/store.ts");
// Libraries

// Utils






var queryParamsToPreserve = {
    kiosk: true,
    autofitpanels: true,
    orgId: true,
};
var PlaylistSrv = /** @class */ (function () {
    /** @ngInject */
    function PlaylistSrv($location, $timeout, backendSrv) {
        this.$location = $location;
        this.$timeout = $timeout;
        this.backendSrv = backendSrv;
        this.numberOfLoops = 0;
    }
    PlaylistSrv.prototype.next = function () {
        var _this = this;
        this.$timeout.cancel(this.cancelPromise);
        var playedAllDashboards = this.index > this.dashboards.length - 1;
        if (playedAllDashboards) {
            this.numberOfLoops++;
            // This does full reload of the playlist to keep memory in check due to existing leaks but at the same time
            // we do not want page to flicker after each full loop.
            if (this.numberOfLoops >= 3) {
                window.location.href = this.startUrl;
                return;
            }
            this.index = 0;
        }
        var dash = this.dashboards[this.index];
        var queryParams = this.$location.search();
        var filteredParams = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.pickBy(queryParams, function (value, key) { return queryParamsToPreserve[key]; });
        var nextDashboardUrl = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_4__["default"].stripBaseFromUrl(dash.url);
        // this is done inside timeout to make sure digest happens after
        // as this can be called from react
        this.$timeout(function () {
            _this.$location.url(nextDashboardUrl + '?' + Object(app_core_utils_url__WEBPACK_IMPORTED_MODULE_1__["toUrlParams"])(filteredParams));
        });
        this.index++;
        this.validPlaylistUrl = nextDashboardUrl;
        this.cancelPromise = this.$timeout(function () { return _this.next(); }, this.interval);
    };
    PlaylistSrv.prototype.prev = function () {
        this.index = Math.max(this.index - 2, 0);
        this.next();
    };
    // Detect url changes not caused by playlist srv and stop playlist
    PlaylistSrv.prototype.storeUpdated = function () {
        var state = app_store_store__WEBPACK_IMPORTED_MODULE_6__["store"].getState();
        if (state.location.path !== this.validPlaylistUrl) {
            this.stop();
        }
    };
    PlaylistSrv.prototype.start = function (playlistId) {
        var _this = this;
        this.stop();
        this.startUrl = window.location.href;
        this.index = 0;
        this.isPlaying = true;
        // setup location tracking
        this.storeUnsub = app_store_store__WEBPACK_IMPORTED_MODULE_6__["store"].subscribe(function () { return _this.storeUpdated(); });
        this.validPlaylistUrl = this.$location.path();
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('playlist-started');
        return this.backendSrv.get("/api/playlists/" + playlistId).then(function (playlist) {
            return _this.backendSrv.get("/api/playlists/" + playlistId + "/dashboards").then(function (dashboards) {
                _this.dashboards = dashboards;
                _this.interval = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_5__["default"].interval_to_ms(playlist.interval);
                _this.next();
            });
        });
    };
    PlaylistSrv.prototype.stop = function () {
        if (this.isPlaying) {
            var queryParams = this.$location.search();
            if (queryParams.kiosk) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('toggle-kiosk-mode', { exit: true });
            }
        }
        this.index = 0;
        this.isPlaying = false;
        if (this.storeUnsub) {
            this.storeUnsub();
        }
        if (this.cancelPromise) {
            this.$timeout.cancel(this.cancelPromise);
        }
        app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('playlist-stopped');
    };
    return PlaylistSrv;
}());

_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].service('playlistSrv', PlaylistSrv);


/***/ }),

/***/ "./public/app/features/playlist/playlists_ctrl.ts":
/*!********************************************************!*\
  !*** ./public/app/features/playlist/playlists_ctrl.ts ***!
  \********************************************************/
/*! exports provided: PlaylistsCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistsCtrl", function() { return PlaylistsCtrl; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../core/core_module */ "./public/app/core/core_module.ts");


var PlaylistsCtrl = /** @class */ (function () {
    /** @ngInject */
    function PlaylistsCtrl($scope, backendSrv, navModelSrv) {
        var _this = this;
        this.$scope = $scope;
        this.backendSrv = backendSrv;
        this.navModel = navModelSrv.getNav('dashboards', 'playlists', 0);
        backendSrv.get('/api/playlists').then(function (result) {
            _this.playlists = result.map(function (item) {
                item.startUrl = "playlists/play/" + item.id;
                return item;
            });
        });
    }
    PlaylistsCtrl.prototype.removePlaylistConfirmed = function (playlist) {
        var _this = this;
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.remove(this.playlists, { id: playlist.id });
        this.backendSrv.delete('/api/playlists/' + playlist.id).then(function () {
            _this.$scope.appEvent('alert-success', ['Playlist deleted', '']);
        }, function () {
            _this.$scope.appEvent('alert-error', ['Unable to delete playlist', '']);
            _this.playlists.push(playlist);
        });
    };
    PlaylistsCtrl.prototype.removePlaylist = function (playlist) {
        var _this = this;
        this.$scope.appEvent('confirm-modal', {
            title: 'Delete',
            text: 'Are you sure you want to delete playlist ' + playlist.name + '?',
            yesText: 'Delete',
            icon: 'fa-trash',
            onConfirm: function () {
                _this.removePlaylistConfirmed(playlist);
            },
        });
    };
    return PlaylistsCtrl;
}());

_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].controller('PlaylistsCtrl', PlaylistsCtrl);


/***/ }),

/***/ "./public/app/features/plugins/PluginSettingsCache.ts":
/*!************************************************************!*\
  !*** ./public/app/features/plugins/PluginSettingsCache.ts ***!
  \************************************************************/
/*! exports provided: getPluginSettings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPluginSettings", function() { return getPluginSettings; });
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");

var pluginInfoCache = {};
function getPluginSettings(pluginId) {
    var v = pluginInfoCache[pluginId];
    if (v) {
        return Promise.resolve(v);
    }
    return Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_0__["getBackendSrv"])()
        .get("/api/plugins/" + pluginId + "/settings")
        .then(function (settings) {
        pluginInfoCache[pluginId] = settings;
        return settings;
    })
        .catch(function (err) {
        // err.isHandled = true;
        return Promise.reject('Unknown Plugin');
    });
}


/***/ }),

/***/ "./public/app/features/plugins/all.ts":
/*!********************************************!*\
  !*** ./public/app/features/plugins/all.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _plugin_page_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./plugin_page_ctrl */ "./public/app/features/plugins/plugin_page_ctrl.ts");
/* harmony import */ var _datasource_srv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./datasource_srv */ "./public/app/features/plugins/datasource_srv.ts");
/* harmony import */ var _plugin_component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./plugin_component */ "./public/app/features/plugins/plugin_component.ts");
/* harmony import */ var _variableQueryEditorLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./variableQueryEditorLoader */ "./public/app/features/plugins/variableQueryEditorLoader.tsx");






/***/ }),

/***/ "./public/app/features/plugins/built_in_plugins.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/plugins/built_in_plugins.ts ***!
  \*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_plugins_panel_text_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/plugins/panel/text/module */ "./public/app/plugins/panel/text/module.ts");
/* harmony import */ var app_plugins_panel_text2_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/plugins/panel/text2/module */ "./public/app/plugins/panel/text2/module.tsx");
/* harmony import */ var app_plugins_panel_graph2_module__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/plugins/panel/graph2/module */ "./public/app/plugins/panel/graph2/module.tsx");
/* harmony import */ var app_plugins_panel_graph_module__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/plugins/panel/graph/module */ "./public/app/plugins/panel/graph/module.ts");
/* harmony import */ var app_plugins_panel_dashlist_module__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/plugins/panel/dashlist/module */ "./public/app/plugins/panel/dashlist/module.ts");
/* harmony import */ var app_plugins_panel_pluginlist_module__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/plugins/panel/pluginlist/module */ "./public/app/plugins/panel/pluginlist/module.ts");
/* harmony import */ var app_plugins_panel_alertlist_module__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/plugins/panel/alertlist/module */ "./public/app/plugins/panel/alertlist/module.ts");
/* harmony import */ var app_plugins_panel_annolist_module__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/plugins/panel/annolist/module */ "./public/app/plugins/panel/annolist/module.ts");
/* harmony import */ var app_plugins_panel_heatmap_module__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/plugins/panel/heatmap/module */ "./public/app/plugins/panel/heatmap/module.ts");
/* harmony import */ var app_plugins_panel_table_module__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! app/plugins/panel/table/module */ "./public/app/plugins/panel/table/module.ts");
/* harmony import */ var app_plugins_panel_table2_module__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! app/plugins/panel/table2/module */ "./public/app/plugins/panel/table2/module.tsx");
/* harmony import */ var app_plugins_panel_singlestat_module__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/plugins/panel/singlestat/module */ "./public/app/plugins/panel/singlestat/module.ts");
/* harmony import */ var app_plugins_panel_singlestat2_module__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! app/plugins/panel/singlestat2/module */ "./public/app/plugins/panel/singlestat2/module.tsx");
/* harmony import */ var app_plugins_panel_gettingstarted_module__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! app/plugins/panel/gettingstarted/module */ "./public/app/plugins/panel/gettingstarted/module.ts");
/* harmony import */ var app_plugins_panel_gauge_module__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! app/plugins/panel/gauge/module */ "./public/app/plugins/panel/gauge/module.tsx");
/* harmony import */ var app_plugins_panel_piechart_module__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! app/plugins/panel/piechart/module */ "./public/app/plugins/panel/piechart/module.tsx");
/* harmony import */ var app_plugins_panel_bargauge_module__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! app/plugins/panel/bargauge/module */ "./public/app/plugins/panel/bargauge/module.tsx");
/* harmony import */ var app_plugins_panel_logs_module__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! app/plugins/panel/logs/module */ "./public/app/plugins/panel/logs/module.tsx");
var _this = undefined;

var graphitePlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | graphitePlugin */ "graphitePlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/graphite/module */ "./public/app/plugins/datasource/graphite/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var cloudwatchPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | cloudwatchPlugin */ "cloudwatchPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/cloudwatch/module */ "./public/app/plugins/datasource/cloudwatch/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var dashboardDSPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() */ 3).then(__webpack_require__.bind(null, /*! app/plugins/datasource/dashboard/module */ "./public/app/plugins/datasource/dashboard/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var elasticsearchPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | elasticsearchPlugin */ "elasticsearchPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/elasticsearch/module */ "./public/app/plugins/datasource/elasticsearch/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var opentsdbPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | opentsdbPlugin */ "opentsdbPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/opentsdb/module */ "./public/app/plugins/datasource/opentsdb/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var grafanaPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | grafanaPlugin */ "grafanaPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/grafana/module */ "./public/app/plugins/datasource/grafana/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var influxdbPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | influxdbPlugin */ "influxdbPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/influxdb/module */ "./public/app/plugins/datasource/influxdb/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var lokiPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | lokiPlugin */ "lokiPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/loki/module */ "./public/app/plugins/datasource/loki/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var mixedPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | mixedPlugin */ "mixedPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/mixed/module */ "./public/app/plugins/datasource/mixed/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var mysqlPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | mysqlPlugin */ "mysqlPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/mysql/module */ "./public/app/plugins/datasource/mysql/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var postgresPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | postgresPlugin */ "postgresPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/postgres/module */ "./public/app/plugins/datasource/postgres/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var prometheusPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | prometheusPlugin */ "prometheusPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/prometheus/module */ "./public/app/plugins/datasource/prometheus/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var mssqlPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | mssqlPlugin */ "mssqlPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/mssql/module */ "./public/app/plugins/datasource/mssql/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var testDataDSPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | testDataDSPlugin */ "testDataDSPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/testdata/module */ "./public/app/plugins/datasource/testdata/module.tsx"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var inputDatasourcePlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | inputDatasourcePlugin */ "inputDatasourcePlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/input/module */ "./public/app/plugins/datasource/input/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var stackdriverPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | stackdriverPlugin */ "stackdriverPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/stackdriver/module */ "./public/app/plugins/datasource/stackdriver/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var azureMonitorPlugin = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | azureMonitorPlugin */ "azureMonitorPlugin").then(__webpack_require__.bind(null, /*! app/plugins/datasource/grafana-azure-monitor-datasource/module */ "./public/app/plugins/datasource/grafana-azure-monitor-datasource/module.tsx"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };


















var exampleApp = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | exampleApp */ "exampleApp").then(__webpack_require__.bind(null, /*! app/plugins/app/example-app/module */ "./public/app/plugins/app/example-app/module.ts"))];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
var builtInPlugins = {
    'app/plugins/datasource/graphite/module': graphitePlugin,
    'app/plugins/datasource/cloudwatch/module': cloudwatchPlugin,
    'app/plugins/datasource/dashboard/module': dashboardDSPlugin,
    'app/plugins/datasource/elasticsearch/module': elasticsearchPlugin,
    'app/plugins/datasource/opentsdb/module': opentsdbPlugin,
    'app/plugins/datasource/grafana/module': grafanaPlugin,
    'app/plugins/datasource/influxdb/module': influxdbPlugin,
    'app/plugins/datasource/loki/module': lokiPlugin,
    'app/plugins/datasource/mixed/module': mixedPlugin,
    'app/plugins/datasource/mysql/module': mysqlPlugin,
    'app/plugins/datasource/postgres/module': postgresPlugin,
    'app/plugins/datasource/mssql/module': mssqlPlugin,
    'app/plugins/datasource/prometheus/module': prometheusPlugin,
    'app/plugins/datasource/testdata/module': testDataDSPlugin,
    'app/plugins/datasource/input/module': inputDatasourcePlugin,
    'app/plugins/datasource/stackdriver/module': stackdriverPlugin,
    'app/plugins/datasource/grafana-azure-monitor-datasource/module': azureMonitorPlugin,
    'app/plugins/panel/text/module': app_plugins_panel_text_module__WEBPACK_IMPORTED_MODULE_1__,
    'app/plugins/panel/text2/module': app_plugins_panel_text2_module__WEBPACK_IMPORTED_MODULE_2__,
    'app/plugins/panel/graph2/module': app_plugins_panel_graph2_module__WEBPACK_IMPORTED_MODULE_3__,
    'app/plugins/panel/graph/module': app_plugins_panel_graph_module__WEBPACK_IMPORTED_MODULE_4__,
    'app/plugins/panel/dashlist/module': app_plugins_panel_dashlist_module__WEBPACK_IMPORTED_MODULE_5__,
    'app/plugins/panel/pluginlist/module': app_plugins_panel_pluginlist_module__WEBPACK_IMPORTED_MODULE_6__,
    'app/plugins/panel/alertlist/module': app_plugins_panel_alertlist_module__WEBPACK_IMPORTED_MODULE_7__,
    'app/plugins/panel/annolist/module': app_plugins_panel_annolist_module__WEBPACK_IMPORTED_MODULE_8__,
    'app/plugins/panel/heatmap/module': app_plugins_panel_heatmap_module__WEBPACK_IMPORTED_MODULE_9__,
    'app/plugins/panel/table/module': app_plugins_panel_table_module__WEBPACK_IMPORTED_MODULE_10__,
    'app/plugins/panel/table2/module': app_plugins_panel_table2_module__WEBPACK_IMPORTED_MODULE_11__,
    'app/plugins/panel/singlestat/module': app_plugins_panel_singlestat_module__WEBPACK_IMPORTED_MODULE_12__,
    'app/plugins/panel/singlestat2/module': app_plugins_panel_singlestat2_module__WEBPACK_IMPORTED_MODULE_13__,
    'app/plugins/panel/gettingstarted/module': app_plugins_panel_gettingstarted_module__WEBPACK_IMPORTED_MODULE_14__,
    'app/plugins/panel/gauge/module': app_plugins_panel_gauge_module__WEBPACK_IMPORTED_MODULE_15__,
    'app/plugins/panel/piechart/module': app_plugins_panel_piechart_module__WEBPACK_IMPORTED_MODULE_16__,
    'app/plugins/panel/bargauge/module': app_plugins_panel_bargauge_module__WEBPACK_IMPORTED_MODULE_17__,
    'app/plugins/panel/logs/module': app_plugins_panel_logs_module__WEBPACK_IMPORTED_MODULE_18__,
    'app/plugins/app/example-app/module': exampleApp,
};
/* harmony default export */ __webpack_exports__["default"] = (builtInPlugins);


/***/ }),

/***/ "./public/app/features/plugins/datasource_srv.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/plugins/datasource_srv.ts ***!
  \*******************************************************/
/*! exports provided: DatasourceSrv, getDatasourceSrv, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DatasourceSrv", function() { return DatasourceSrv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDatasourceSrv", function() { return getDatasourceSrv; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _plugin_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./plugin_loader */ "./public/app/features/plugins/plugin_loader.ts");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
// Libraries


// Services & Utils



var DatasourceSrv = /** @class */ (function () {
    /** @ngInject */
    function DatasourceSrv($q, $injector, $rootScope, templateSrv) {
        this.$q = $q;
        this.$injector = $injector;
        this.$rootScope = $rootScope;
        this.templateSrv = templateSrv;
        this.init();
    }
    DatasourceSrv.prototype.init = function () {
        this.datasources = {};
    };
    DatasourceSrv.prototype.get = function (name, scopedVars) {
        if (!name) {
            return this.get(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].defaultDatasource);
        }
        // Interpolation here is to support template variable in data source selection
        name = this.templateSrv.replace(name, scopedVars, function (value, variable) {
            if (Array.isArray(value)) {
                return value[0];
            }
            return value;
        });
        if (name === 'default') {
            return this.get(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].defaultDatasource);
        }
        if (this.datasources[name]) {
            return this.$q.when(this.datasources[name]);
        }
        return this.loadDatasource(name);
    };
    DatasourceSrv.prototype.loadDatasource = function (name) {
        var _this = this;
        var dsConfig = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].datasources[name];
        if (!dsConfig) {
            return this.$q.reject({ message: 'Datasource named ' + name + ' was not found' });
        }
        var deferred = this.$q.defer();
        Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_3__["importDataSourcePlugin"])(dsConfig.meta)
            .then(function (dsPlugin) {
            // check if its in cache now
            if (_this.datasources[name]) {
                deferred.resolve(_this.datasources[name]);
                return;
            }
            // If there is only one constructor argument it is instanceSettings
            var useAngular = dsPlugin.DataSourceClass.length !== 1;
            var instance = useAngular
                ? _this.$injector.instantiate(dsPlugin.DataSourceClass, {
                    instanceSettings: dsConfig,
                })
                : new dsPlugin.DataSourceClass(dsConfig);
            instance.components = dsPlugin.components;
            instance.meta = dsConfig.meta;
            // store in instance cache
            _this.datasources[name] = instance;
            deferred.resolve(instance);
        })
            .catch(function (err) {
            _this.$rootScope.appEvent('alert-error', [dsConfig.name + ' plugin failed', err.toString()]);
        });
        return deferred.promise;
    };
    DatasourceSrv.prototype.getAll = function () {
        var datasources = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].datasources;
        return Object.keys(datasources).map(function (name) { return datasources[name]; });
    };
    DatasourceSrv.prototype.getExternal = function () {
        var datasources = this.getAll().filter(function (ds) { return !ds.meta.builtIn; });
        return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.sortBy(datasources, ['name']);
    };
    DatasourceSrv.prototype.getAnnotationSources = function () {
        var sources = [];
        this.addDataSourceVariables(sources);
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].datasources, function (value) {
            if (value.meta && value.meta.annotations) {
                sources.push(value);
            }
        });
        return sources;
    };
    DatasourceSrv.prototype.getMetricSources = function (options) {
        var metricSources = [];
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each(app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].datasources, function (value, key) {
            if (value.meta && value.meta.metrics) {
                var metricSource = { value: key, name: key, meta: value.meta, sort: key };
                //Make sure grafana and mixed are sorted at the bottom
                if (value.meta.id === 'grafana') {
                    metricSource.sort = String.fromCharCode(253);
                }
                else if (value.meta.id === 'dashboard') {
                    metricSource.sort = String.fromCharCode(254);
                }
                else if (value.meta.id === 'mixed') {
                    metricSource.sort = String.fromCharCode(255);
                }
                metricSources.push(metricSource);
                if (key === app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].defaultDatasource) {
                    metricSource = { value: null, name: 'default', meta: value.meta, sort: key };
                    metricSources.push(metricSource);
                }
            }
        });
        if (!options || !options.skipVariables) {
            this.addDataSourceVariables(metricSources);
        }
        metricSources.sort(function (a, b) {
            if (a.sort.toLowerCase() > b.sort.toLowerCase()) {
                return 1;
            }
            if (a.sort.toLowerCase() < b.sort.toLowerCase()) {
                return -1;
            }
            return 0;
        });
        return metricSources;
    };
    DatasourceSrv.prototype.addDataSourceVariables = function (list) {
        // look for data source variables
        for (var i = 0; i < this.templateSrv.variables.length; i++) {
            var variable = this.templateSrv.variables[i];
            if (variable.type !== 'datasource') {
                continue;
            }
            var first = variable.current.value;
            if (first === 'default') {
                first = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].defaultDatasource;
            }
            var ds = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].datasources[first];
            if (ds) {
                var key = "$" + variable.name;
                list.push({
                    name: key,
                    value: key,
                    meta: ds.meta,
                    sort: key,
                });
            }
        }
    };
    return DatasourceSrv;
}());

function getDatasourceSrv() {
    return Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_4__["getDataSourceSrv"])();
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].service('datasourceSrv', DatasourceSrv);
/* harmony default export */ __webpack_exports__["default"] = (DatasourceSrv);


/***/ }),

/***/ "./public/app/features/plugins/plugin_component.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/plugins/plugin_component.ts ***!
  \*********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _plugin_loader__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./plugin_loader */ "./public/app/features/plugins/plugin_loader.ts");





/** @ngInject */
function pluginDirectiveLoader($compile, datasourceSrv, $rootScope, $q, $http, $templateCache, $timeout) {
    function getTemplate(component) {
        if (component.template) {
            return $q.when(component.template);
        }
        var cached = $templateCache.get(component.templateUrl);
        if (cached) {
            return $q.when(cached);
        }
        return $http.get(component.templateUrl).then(function (res) {
            return res.data;
        });
    }
    function relativeTemplateUrlToAbs(templateUrl, baseUrl) {
        if (!templateUrl) {
            return undefined;
        }
        if (templateUrl.indexOf('public') === 0) {
            return templateUrl;
        }
        return baseUrl + '/' + templateUrl;
    }
    function getPluginComponentDirective(options) {
        // handle relative template urls for plugin templates
        options.Component.templateUrl = relativeTemplateUrlToAbs(options.Component.templateUrl, options.baseUrl);
        return function () {
            return {
                templateUrl: options.Component.templateUrl,
                template: options.Component.template,
                restrict: 'E',
                controller: options.Component,
                controllerAs: 'ctrl',
                bindToController: true,
                scope: options.bindings,
                link: function (scope, elem, attrs, ctrl) {
                    if (ctrl.link) {
                        ctrl.link(scope, elem, attrs, ctrl);
                    }
                    if (ctrl.init) {
                        ctrl.init();
                    }
                },
            };
        };
    }
    function loadPanelComponentInfo(scope, attrs) {
        var componentInfo = {
            name: 'panel-plugin-' + scope.panel.type,
            bindings: { dashboard: '=', panel: '=', row: '=' },
            attrs: {
                dashboard: 'dashboard',
                panel: 'panel',
                class: 'panel-height-helper',
            },
        };
        var panelInfo = app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].panels[scope.panel.type];
        return Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_4__["importPanelPlugin"])(panelInfo.id).then(function (panelPlugin) {
            var PanelCtrl = panelPlugin.angularPanelCtrl;
            componentInfo.Component = PanelCtrl;
            if (!PanelCtrl || PanelCtrl.registered) {
                return componentInfo;
            }
            if (PanelCtrl.templatePromise) {
                return PanelCtrl.templatePromise.then(function (res) {
                    return componentInfo;
                });
            }
            if (panelInfo) {
                PanelCtrl.templateUrl = relativeTemplateUrlToAbs(PanelCtrl.templateUrl, panelInfo.baseUrl);
            }
            PanelCtrl.templatePromise = getTemplate(PanelCtrl).then(function (template) {
                PanelCtrl.templateUrl = null;
                PanelCtrl.template = "<grafana-panel ctrl=\"ctrl\" class=\"panel-height-helper\">" + template + "</grafana-panel>";
                return componentInfo;
            });
            return PanelCtrl.templatePromise;
        });
    }
    function getModule(scope, attrs) {
        switch (attrs.type) {
            // QueryCtrl
            case 'query-ctrl': {
                var ds = scope.ctrl.datasource;
                return $q.when({
                    baseUrl: ds.meta.baseUrl,
                    name: 'query-ctrl-' + ds.meta.id,
                    bindings: { target: '=', panelCtrl: '=', datasource: '=' },
                    attrs: {
                        target: 'ctrl.target',
                        'panel-ctrl': 'ctrl',
                        datasource: 'ctrl.datasource',
                    },
                    Component: ds.components.QueryCtrl,
                });
            }
            // Annotations
            case 'annotations-query-ctrl': {
                return Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_4__["importDataSourcePlugin"])(scope.ctrl.currentDatasource.meta).then(function (dsPlugin) {
                    return {
                        baseUrl: scope.ctrl.currentDatasource.meta.baseUrl,
                        name: 'annotations-query-ctrl-' + scope.ctrl.currentDatasource.meta.id,
                        bindings: { annotation: '=', datasource: '=' },
                        attrs: {
                            annotation: 'ctrl.currentAnnotation',
                            datasource: 'ctrl.currentDatasource',
                        },
                        Component: dsPlugin.components.AnnotationsQueryCtrl,
                    };
                });
            }
            // Datasource ConfigCtrl
            case 'datasource-config-ctrl': {
                var dsMeta_1 = scope.ctrl.datasourceMeta;
                return Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_4__["importDataSourcePlugin"])(dsMeta_1).then(function (dsPlugin) {
                    scope.$watch('ctrl.current', function () {
                        scope.onModelChanged(scope.ctrl.current);
                    }, true);
                    return {
                        baseUrl: dsMeta_1.baseUrl,
                        name: 'ds-config-' + dsMeta_1.id,
                        bindings: { meta: '=', current: '=' },
                        attrs: { meta: 'ctrl.datasourceMeta', current: 'ctrl.current' },
                        Component: dsPlugin.angularConfigCtrl,
                    };
                });
            }
            // AppConfigCtrl
            case 'app-config-ctrl': {
                var model_1 = scope.ctrl.model;
                return Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_4__["importAppPlugin"])(model_1).then(function (appPlugin) {
                    return {
                        baseUrl: model_1.baseUrl,
                        name: 'app-config-' + model_1.id,
                        bindings: { appModel: '=', appEditCtrl: '=' },
                        attrs: { 'app-model': 'ctrl.model', 'app-edit-ctrl': 'ctrl' },
                        Component: appPlugin.angularConfigCtrl,
                    };
                });
            }
            // App Page
            case 'app-page': {
                var appModel_1 = scope.ctrl.appModel;
                return Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_4__["importAppPlugin"])(appModel_1).then(function (appPlugin) {
                    return {
                        baseUrl: appModel_1.baseUrl,
                        name: 'app-page-' + appModel_1.id + '-' + scope.ctrl.page.slug,
                        bindings: { appModel: '=' },
                        attrs: { 'app-model': 'ctrl.appModel' },
                        Component: appPlugin.angularPages[scope.ctrl.page.component],
                    };
                });
            }
            // Panel
            case 'panel': {
                return loadPanelComponentInfo(scope, attrs);
            }
            default: {
                return $q.reject({
                    message: 'Could not find component type: ' + attrs.type,
                });
            }
        }
    }
    function appendAndCompile(scope, elem, componentInfo) {
        var child = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(document.createElement(componentInfo.name));
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.each(componentInfo.attrs, function (value, key) {
            child.attr(key, value);
        });
        $compile(child)(scope);
        elem.empty();
        // let a binding digest cycle complete before adding to dom
        setTimeout(function () {
            scope.$applyAsync(function () {
                elem.append(child);
                setTimeout(function () {
                    scope.$applyAsync(function () {
                        scope.$broadcast('component-did-mount');
                    });
                });
            });
        });
    }
    function registerPluginComponent(scope, elem, attrs, componentInfo) {
        if (componentInfo.notFound) {
            elem.empty();
            return;
        }
        if (!componentInfo.Component) {
            throw {
                message: 'Failed to find exported plugin component for ' + componentInfo.name,
            };
        }
        if (!componentInfo.Component.registered) {
            var directiveName = attrs.$normalize(componentInfo.name);
            var directiveFn = getPluginComponentDirective(componentInfo);
            app_core_core_module__WEBPACK_IMPORTED_MODULE_3__["default"].directive(directiveName, directiveFn);
            componentInfo.Component.registered = true;
        }
        appendAndCompile(scope, elem, componentInfo);
    }
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            getModule(scope, attrs)
                .then(function (componentInfo) {
                registerPluginComponent(scope, elem, attrs, componentInfo);
            })
                .catch(function (err) {
                console.log('Plugin component error', err);
            });
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_3__["default"].directive('pluginComponent', pluginDirectiveLoader);


/***/ }),

/***/ "./public/app/features/plugins/plugin_loader.ts":
/*!******************************************************!*\
  !*** ./public/app/features/plugins/plugin_loader.ts ***!
  \******************************************************/
/*! exports provided: importPluginModule, importDataSourcePlugin, importAppPlugin, importPanelPlugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "importPluginModule", function() { return importPluginModule; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "importDataSourcePlugin", function() { return importDataSourcePlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "importAppPlugin", function() { return importAppPlugin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "importPanelPlugin", function() { return importPanelPlugin; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! moment */ "./node_modules/moment/moment.js");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! prismjs */ "./node_modules/prismjs/prism.js");
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(prismjs__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var slate__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! slate */ "./node_modules/slate/lib/slate.es.js");
/* harmony import */ var _grafana_slate_react__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @grafana/slate-react */ "./node_modules/@grafana/slate-react/lib/slate-react.es.js");
/* harmony import */ var slate_plain_serializer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! slate-plain-serializer */ "./node_modules/slate-plain-serializer/lib/slate-plain-serializer.es.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! redux */ "./node_modules/redux/es/redux.js");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_time_series2__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! app/core/time_series2 */ "./public/app/core/time_series2.ts");
/* harmony import */ var app_core_table_model__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! app/core/table_model */ "./public/app/core/table_model.ts");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_utils_file_export__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! app/core/utils/file_export */ "./public/app/core/utils/file_export.ts");
/* harmony import */ var app_core_utils_flatten__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! app/core/utils/flatten */ "./public/app/core/utils/flatten.ts");
/* harmony import */ var app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! app/core/utils/ticks */ "./public/app/core/utils/ticks.ts");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");
/* harmony import */ var app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! app/core/services/impression_srv */ "./public/app/core/services/impression_srv.ts");
/* harmony import */ var _built_in_plugins__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./built_in_plugins */ "./public/app/features/plugins/built_in_plugins.ts");
/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! d3 */ "./node_modules/d3/index.js");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm5/index.js");
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! rxjs/operators */ "./node_modules/rxjs/_esm5/operators/index.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! vendor/flot/jquery.flot */ "./public/vendor/flot/jquery.flot.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var vendor_flot_jquery_flot_selection__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! vendor/flot/jquery.flot.selection */ "./public/vendor/flot/jquery.flot.selection.js");
/* harmony import */ var vendor_flot_jquery_flot_selection__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_selection__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var vendor_flot_jquery_flot_time__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! vendor/flot/jquery.flot.time */ "./public/vendor/flot/jquery.flot.time.js");
/* harmony import */ var vendor_flot_jquery_flot_time__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_time__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var vendor_flot_jquery_flot_stack__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! vendor/flot/jquery.flot.stack */ "./public/vendor/flot/jquery.flot.stack.js");
/* harmony import */ var vendor_flot_jquery_flot_stack__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_stack__WEBPACK_IMPORTED_MODULE_35__);
/* harmony import */ var vendor_flot_jquery_flot_pie__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! vendor/flot/jquery.flot.pie */ "./public/vendor/flot/jquery.flot.pie.js");
/* harmony import */ var vendor_flot_jquery_flot_pie__WEBPACK_IMPORTED_MODULE_36___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_pie__WEBPACK_IMPORTED_MODULE_36__);
/* harmony import */ var vendor_flot_jquery_flot_stackpercent__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! vendor/flot/jquery.flot.stackpercent */ "./public/vendor/flot/jquery.flot.stackpercent.js");
/* harmony import */ var vendor_flot_jquery_flot_stackpercent__WEBPACK_IMPORTED_MODULE_37___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_stackpercent__WEBPACK_IMPORTED_MODULE_37__);
/* harmony import */ var vendor_flot_jquery_flot_fillbelow__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! vendor/flot/jquery.flot.fillbelow */ "./public/vendor/flot/jquery.flot.fillbelow.js");
/* harmony import */ var vendor_flot_jquery_flot_fillbelow__WEBPACK_IMPORTED_MODULE_38___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_fillbelow__WEBPACK_IMPORTED_MODULE_38__);
/* harmony import */ var vendor_flot_jquery_flot_crosshair__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! vendor/flot/jquery.flot.crosshair */ "./public/vendor/flot/jquery.flot.crosshair.js");
/* harmony import */ var vendor_flot_jquery_flot_crosshair__WEBPACK_IMPORTED_MODULE_39___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_crosshair__WEBPACK_IMPORTED_MODULE_39__);
/* harmony import */ var vendor_flot_jquery_flot_dashes__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! vendor/flot/jquery.flot.dashes */ "./public/vendor/flot/jquery.flot.dashes.js");
/* harmony import */ var vendor_flot_jquery_flot_dashes__WEBPACK_IMPORTED_MODULE_40___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_dashes__WEBPACK_IMPORTED_MODULE_40__);
/* harmony import */ var vendor_flot_jquery_flot_gauge__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! vendor/flot/jquery.flot.gauge */ "./public/vendor/flot/jquery.flot.gauge.js");
/* harmony import */ var vendor_flot_jquery_flot_gauge__WEBPACK_IMPORTED_MODULE_41___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_gauge__WEBPACK_IMPORTED_MODULE_41__);
/* harmony import */ var _dashboard_dashgrid_PanelPluginError__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ../dashboard/dashgrid/PanelPluginError */ "./public/app/features/dashboard/dashgrid/PanelPluginError.tsx");
var e_1, _a;




// tslint:disable:import-blacklist



// Experimental module exports


// @ts-ignore

// @ts-ignore






















// rxjs


// add cache busting
var bust = "?_cache=" + Date.now();
function locate(load) {
    return load.address + bust;
}
_grafana_runtime__WEBPACK_IMPORTED_MODULE_29__["SystemJS"].registry.set('plugin-loader', _grafana_runtime__WEBPACK_IMPORTED_MODULE_29__["SystemJS"].newModule({ locate: locate }));
_grafana_runtime__WEBPACK_IMPORTED_MODULE_29__["SystemJS"].config({
    baseURL: 'public',
    defaultExtension: 'js',
    packages: {
        plugins: {
            defaultExtension: 'js',
        },
    },
    map: {
        text: 'vendor/plugin-text/text.js',
        css: 'vendor/plugin-css/css.js',
    },
    meta: {
        '/*': {
            esModule: true,
            authorization: true,
            loader: 'plugin-loader',
        },
    },
});
function exposeToPlugin(name, component) {
    _grafana_runtime__WEBPACK_IMPORTED_MODULE_29__["SystemJS"].registerDynamic(name, [], true, function (require, exports, module) {
        module.exports = component;
    });
}
exposeToPlugin('@grafana/data', _grafana_data__WEBPACK_IMPORTED_MODULE_20__);
exposeToPlugin('@grafana/ui', _grafana_ui__WEBPACK_IMPORTED_MODULE_19__);
exposeToPlugin('@grafana/runtime', _grafana_runtime__WEBPACK_IMPORTED_MODULE_29__);
exposeToPlugin('lodash', lodash__WEBPACK_IMPORTED_MODULE_1___default.a);
exposeToPlugin('moment', moment__WEBPACK_IMPORTED_MODULE_4___default.a);
exposeToPlugin('jquery', jquery__WEBPACK_IMPORTED_MODULE_6___default.a);
exposeToPlugin('angular', angular__WEBPACK_IMPORTED_MODULE_5___default.a);
exposeToPlugin('d3', d3__WEBPACK_IMPORTED_MODULE_27__);
exposeToPlugin('rxjs', rxjs__WEBPACK_IMPORTED_MODULE_30__);
exposeToPlugin('rxjs/operators', rxjs_operators__WEBPACK_IMPORTED_MODULE_31__);
// Experimental modules
exposeToPlugin('prismjs', prismjs__WEBPACK_IMPORTED_MODULE_7___default.a);
exposeToPlugin('slate', slate__WEBPACK_IMPORTED_MODULE_8__["default"]);
exposeToPlugin('@grafana/slate-react', _grafana_slate_react__WEBPACK_IMPORTED_MODULE_9__["default"]);
exposeToPlugin('slate-plain-serializer', slate_plain_serializer__WEBPACK_IMPORTED_MODULE_10__["default"]);
exposeToPlugin('react', react__WEBPACK_IMPORTED_MODULE_11___default.a);
exposeToPlugin('react-dom', react_dom__WEBPACK_IMPORTED_MODULE_12___default.a);
exposeToPlugin('react-redux', react_redux__WEBPACK_IMPORTED_MODULE_13__["default"]);
exposeToPlugin('redux', redux__WEBPACK_IMPORTED_MODULE_14__["default"]);
exposeToPlugin('emotion', emotion__WEBPACK_IMPORTED_MODULE_28__);
exposeToPlugin('app/features/dashboard/impression_store', {
    impressions: app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_25__["default"],
    __esModule: true,
});
/**
 * NOTE: this is added temporarily while we explore a long term solution
 * If you use this export, only use the:
 *  get/delete/post/patch/request methods
 */
exposeToPlugin('app/core/services/backend_srv', {
    BackendSrv: app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_24__["BackendSrv"],
    getBackendSrv: app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_24__["getBackendSrv"],
});
exposeToPlugin('app/plugins/sdk', app_plugins_sdk__WEBPACK_IMPORTED_MODULE_2__);
exposeToPlugin('app/core/utils/datemath', _grafana_data__WEBPACK_IMPORTED_MODULE_20__["dateMath"]);
exposeToPlugin('app/core/utils/file_export', app_core_utils_file_export__WEBPACK_IMPORTED_MODULE_21__);
exposeToPlugin('app/core/utils/flatten', app_core_utils_flatten__WEBPACK_IMPORTED_MODULE_22__);
exposeToPlugin('app/core/utils/kbn', app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__["default"]);
exposeToPlugin('app/core/utils/ticks', app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_23__);
exposeToPlugin('app/core/config', app_core_config__WEBPACK_IMPORTED_MODULE_15__["default"]);
exposeToPlugin('app/core/time_series', app_core_time_series2__WEBPACK_IMPORTED_MODULE_16__["default"]);
exposeToPlugin('app/core/time_series2', app_core_time_series2__WEBPACK_IMPORTED_MODULE_16__["default"]);
exposeToPlugin('app/core/table_model', app_core_table_model__WEBPACK_IMPORTED_MODULE_17__["default"]);
exposeToPlugin('app/core/app_events', app_core_core__WEBPACK_IMPORTED_MODULE_18__["appEvents"]);
exposeToPlugin('app/core/core_module', app_core_core__WEBPACK_IMPORTED_MODULE_18__["coreModule"]);
exposeToPlugin('app/core/core', {
    coreModule: app_core_core__WEBPACK_IMPORTED_MODULE_18__["coreModule"],
    appEvents: app_core_core__WEBPACK_IMPORTED_MODULE_18__["appEvents"],
    contextSrv: app_core_core__WEBPACK_IMPORTED_MODULE_18__["contextSrv"],
    __esModule: true,
});










var flotDeps = [
    'jquery.flot',
    'jquery.flot.pie',
    'jquery.flot.time',
    'jquery.flot.fillbelow',
    'jquery.flot.crosshair',
    'jquery.flot.stack',
    'jquery.flot.selection',
    'jquery.flot.stackpercent',
    'jquery.flot.events',
    'jquery.flot.gauge',
];
try {
    for (var flotDeps_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](flotDeps), flotDeps_1_1 = flotDeps_1.next(); !flotDeps_1_1.done; flotDeps_1_1 = flotDeps_1.next()) {
        var flotDep = flotDeps_1_1.value;
        exposeToPlugin(flotDep, { fakeDep: 1 });
    }
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
    try {
        if (flotDeps_1_1 && !flotDeps_1_1.done && (_a = flotDeps_1.return)) _a.call(flotDeps_1);
    }
    finally { if (e_1) throw e_1.error; }
}
function importPluginModule(path) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, Promise, function () {
        var builtIn;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    builtIn = _built_in_plugins__WEBPACK_IMPORTED_MODULE_26__["default"][path];
                    if (!builtIn) return [3 /*break*/, 3];
                    if (!(typeof builtIn === 'function')) return [3 /*break*/, 2];
                    return [4 /*yield*/, builtIn()];
                case 1: return [2 /*return*/, _a.sent()];
                case 2: return [2 /*return*/, Promise.resolve(builtIn)];
                case 3: return [2 /*return*/, _grafana_runtime__WEBPACK_IMPORTED_MODULE_29__["SystemJS"].import(path)];
            }
        });
    });
}
function importDataSourcePlugin(meta) {
    return importPluginModule(meta.module).then(function (pluginExports) {
        if (pluginExports.plugin) {
            var dsPlugin = pluginExports.plugin;
            dsPlugin.meta = meta;
            return dsPlugin;
        }
        if (pluginExports.Datasource) {
            var dsPlugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_19__["DataSourcePlugin"](pluginExports.Datasource);
            dsPlugin.setComponentsFromLegacyExports(pluginExports);
            dsPlugin.meta = meta;
            return dsPlugin;
        }
        throw new Error('Plugin module is missing DataSourcePlugin or Datasource constructor export');
    });
}
function importAppPlugin(meta) {
    return importPluginModule(meta.module).then(function (pluginExports) {
        var plugin = pluginExports.plugin ? pluginExports.plugin : new _grafana_ui__WEBPACK_IMPORTED_MODULE_19__["AppPlugin"]();
        plugin.init(meta);
        plugin.meta = meta;
        plugin.setComponentsFromLegacyExports(pluginExports);
        return plugin;
    });
}

var panelCache = {};
function importPanelPlugin(id) {
    var loaded = panelCache[id];
    if (loaded) {
        return Promise.resolve(loaded);
    }
    var meta = app_core_config__WEBPACK_IMPORTED_MODULE_15__["default"].panels[id];
    if (!meta) {
        return Promise.resolve(Object(_dashboard_dashgrid_PanelPluginError__WEBPACK_IMPORTED_MODULE_42__["getPanelPluginNotFound"])(id));
    }
    return importPluginModule(meta.module)
        .then(function (pluginExports) {
        if (pluginExports.plugin) {
            return pluginExports.plugin;
        }
        else if (pluginExports.PanelCtrl) {
            var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_19__["PanelPlugin"](null);
            plugin.angularPanelCtrl = pluginExports.PanelCtrl;
            return plugin;
        }
        throw new Error('missing export: plugin or PanelCtrl');
    })
        .then(function (plugin) {
        plugin.meta = meta;
        return (panelCache[meta.id] = plugin);
    })
        .catch(function (err) {
        // TODO, maybe a different error plugin
        console.warn('Error loading panel plugin: ' + id, err);
        return Object(_dashboard_dashgrid_PanelPluginError__WEBPACK_IMPORTED_MODULE_42__["getPanelPluginLoadError"])(meta, err);
    });
}


/***/ }),

/***/ "./public/app/features/plugins/plugin_page_ctrl.ts":
/*!*********************************************************!*\
  !*** ./public/app/features/plugins/plugin_page_ctrl.ts ***!
  \*********************************************************/
/*! exports provided: AppPageCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppPageCtrl", function() { return AppPageCtrl; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _PluginSettingsCache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./PluginSettingsCache */ "./public/app/features/plugins/PluginSettingsCache.ts");



var AppPageCtrl = /** @class */ (function () {
    /** @ngInject */
    function AppPageCtrl($routeParams, $rootScope, navModelSrv, $q) {
        var _this = this;
        this.$routeParams = $routeParams;
        this.$rootScope = $rootScope;
        this.navModelSrv = navModelSrv;
        this.$q = $q;
        this.pluginId = $routeParams.pluginId;
        this.$q
            .when(Object(_PluginSettingsCache__WEBPACK_IMPORTED_MODULE_2__["getPluginSettings"])(this.pluginId))
            .then(function (settings) {
            _this.initPage(settings);
        })
            .catch(function (err) {
            _this.$rootScope.appEvent('alert-error', ['Unknown Plugin', '']);
            _this.navModel = _this.navModelSrv.getNotFoundNav();
        });
    }
    AppPageCtrl.prototype.initPage = function (app) {
        this.appModel = app;
        this.page = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(app.includes, { slug: this.$routeParams.slug });
        if (!this.page) {
            this.$rootScope.appEvent('alert-error', ['App Page Not Found', '']);
            this.navModel = this.navModelSrv.getNotFoundNav();
            return;
        }
        if (app.type !== 'app' || !app.enabled) {
            this.$rootScope.appEvent('alert-error', ['Application Not Enabled', '']);
            this.navModel = this.navModelSrv.getNotFoundNav();
            return;
        }
        var pluginNav = this.navModelSrv.getNav('plugin-page-' + app.id);
        this.navModel = {
            main: {
                img: app.info.logos.large,
                subTitle: app.name,
                url: '',
                text: this.page.name,
                breadcrumbs: [{ title: app.name, url: pluginNav.main.url }],
            },
        };
    };
    return AppPageCtrl;
}());

angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('grafana.controllers').controller('AppPageCtrl', AppPageCtrl);


/***/ }),

/***/ "./public/app/features/plugins/state/actions.ts":
/*!******************************************************!*\
  !*** ./public/app/features/plugins/state/actions.ts ***!
  \******************************************************/
/*! exports provided: ActionTypes, setPluginsLayoutMode, setPluginsSearchQuery, loadPlugins, loadPluginDashboards */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPluginsLayoutMode", function() { return setPluginsLayoutMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPluginsSearchQuery", function() { return setPluginsSearchQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPlugins", function() { return loadPlugins; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPluginDashboards", function() { return loadPluginDashboards; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");


var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadPlugins"] = "LOAD_PLUGINS";
    ActionTypes["LoadPluginDashboards"] = "LOAD_PLUGIN_DASHBOARDS";
    ActionTypes["LoadedPluginDashboards"] = "LOADED_PLUGIN_DASHBOARDS";
    ActionTypes["SetPluginsSearchQuery"] = "SET_PLUGIN_SEARCH_QUERY";
    ActionTypes["SetLayoutMode"] = "SET_LAYOUT_MODE";
})(ActionTypes || (ActionTypes = {}));
var setPluginsLayoutMode = function (mode) { return ({
    type: ActionTypes.SetLayoutMode,
    payload: mode,
}); };
var setPluginsSearchQuery = function (query) { return ({
    type: ActionTypes.SetPluginsSearchQuery,
    payload: query,
}); };
var pluginsLoaded = function (plugins) { return ({
    type: ActionTypes.LoadPlugins,
    payload: plugins,
}); };
var pluginDashboardsLoad = function () { return ({
    type: ActionTypes.LoadPluginDashboards,
}); };
var pluginDashboardsLoaded = function (dashboards) { return ({
    type: ActionTypes.LoadedPluginDashboards,
    payload: dashboards,
}); };
function loadPlugins() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var result;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('api/plugins', { embedded: 0 })];
                case 1:
                    result = _a.sent();
                    dispatch(pluginsLoaded(result));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadPluginDashboards() {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var dataSourceType, response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    dispatch(pluginDashboardsLoad());
                    dataSourceType = getStore().dataSources.dataSource.type;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("api/plugins/" + dataSourceType + "/dashboards")];
                case 1:
                    response = _a.sent();
                    dispatch(pluginDashboardsLoaded(response));
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/plugins/state/reducers.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/plugins/state/reducers.ts ***!
  \*******************************************************/
/*! exports provided: initialState, pluginsReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pluginsReducer", function() { return pluginsReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/plugins/state/actions.ts");
/* harmony import */ var _core_components_LayoutSelector_LayoutSelector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../core/components/LayoutSelector/LayoutSelector */ "./public/app/core/components/LayoutSelector/LayoutSelector.tsx");



var initialState = {
    plugins: [],
    searchQuery: '',
    layoutMode: _core_components_LayoutSelector_LayoutSelector__WEBPACK_IMPORTED_MODULE_2__["LayoutModes"].Grid,
    hasFetched: false,
    dashboards: [],
    isLoadingPluginDashboards: false,
};
var pluginsReducer = function (state, action) {
    if (state === void 0) { state = initialState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadPlugins:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hasFetched: true, plugins: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetPluginsSearchQuery:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchQuery: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetLayoutMode:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { layoutMode: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadPluginDashboards:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dashboards: [], isLoadingPluginDashboards: true });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadedPluginDashboards:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { dashboards: action.payload, isLoadingPluginDashboards: false });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    plugins: pluginsReducer,
});


/***/ }),

/***/ "./public/app/features/plugins/variableQueryEditorLoader.tsx":
/*!*******************************************************************!*\
  !*** ./public/app/features/plugins/variableQueryEditorLoader.tsx ***!
  \*******************************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _plugin_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./plugin_loader */ "./public/app/features/plugins/plugin_loader.ts");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _templating_DefaultVariableQueryEditor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../templating/DefaultVariableQueryEditor */ "./public/app/features/templating/DefaultVariableQueryEditor.tsx");






function loadComponent(meta) {
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
        var dsPlugin;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_plugin_loader__WEBPACK_IMPORTED_MODULE_2__["importDataSourcePlugin"])(meta)];
                case 1:
                    dsPlugin = _a.sent();
                    if (dsPlugin.components.VariableQueryEditor) {
                        return [2 /*return*/, dsPlugin.components.VariableQueryEditor];
                    }
                    else {
                        return [2 /*return*/, _templating_DefaultVariableQueryEditor__WEBPACK_IMPORTED_MODULE_5__["default"]];
                    }
                    return [2 /*return*/];
            }
        });
    });
}
/** @ngInject */
function variableQueryEditorLoader(templateSrv) {
    var _this = this;
    return {
        restrict: 'E',
        link: function (scope, elem) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            var Component, props;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, loadComponent(scope.currentDatasource.meta)];
                    case 1:
                        Component = _a.sent();
                        props = {
                            datasource: scope.currentDatasource,
                            query: scope.current.query,
                            onChange: scope.onQueryChange,
                            templateSrv: templateSrv,
                        };
                        react_dom__WEBPACK_IMPORTED_MODULE_4___default.a.render(react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Component, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props)), elem[0]);
                        scope.$on('$destroy', function () {
                            react_dom__WEBPACK_IMPORTED_MODULE_4___default.a.unmountComponentAtNode(elem[0]);
                        });
                        return [2 /*return*/];
                }
            });
        }); },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('variableQueryEditorLoader', variableQueryEditorLoader);


/***/ }),

/***/ "./public/app/features/profile/ProfileCtrl.ts":
/*!****************************************************!*\
  !*** ./public/app/features/profile/ProfileCtrl.ts ***!
  \****************************************************/
/*! exports provided: ProfileCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ProfileCtrl", function() { return ProfileCtrl; });
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");


var ProfileCtrl = /** @class */ (function () {
    /** @ngInject */
    function ProfileCtrl(backendSrv, navModelSrv) {
        this.backendSrv = backendSrv;
        this.sessions = [];
        this.getUserSessions();
        this.navModel = navModelSrv.getNav('profile', 'profile-settings', 0);
    }
    ProfileCtrl.prototype.getUserSessions = function () {
        var _this = this;
        this.backendSrv.get('/api/user/auth-tokens').then(function (sessions) {
            sessions.reverse();
            var found = sessions.findIndex(function (session) {
                return session.isActive;
            });
            if (found) {
                var now = sessions[found];
                sessions.splice(found, found);
                sessions.unshift(now);
            }
            _this.sessions = sessions.map(function (session) {
                return {
                    id: session.id,
                    isActive: session.isActive,
                    seenAt: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["dateTime"])(session.seenAt).fromNow(),
                    createdAt: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["dateTime"])(session.createdAt).format('MMMM DD, YYYY'),
                    clientIp: session.clientIp,
                    browser: session.browser,
                    browserVersion: session.browserVersion,
                    os: session.os,
                    osVersion: session.osVersion,
                    device: session.device,
                };
            });
        });
    };
    ProfileCtrl.prototype.revokeUserSession = function (tokenId) {
        var _this = this;
        this.backendSrv
            .post('/api/user/revoke-auth-token', {
            authTokenId: tokenId,
        })
            .then(function () {
            _this.sessions = _this.sessions.filter(function (session) {
                if (session.id === tokenId) {
                    return false;
                }
                return true;
            });
        });
    };
    return ProfileCtrl;
}());

app_core_core__WEBPACK_IMPORTED_MODULE_0__["coreModule"].controller('ProfileCtrl', ProfileCtrl);


/***/ }),

/***/ "./public/app/features/profile/ReactProfileWrapper.tsx":
/*!*************************************************************!*\
  !*** ./public/app/features/profile/ReactProfileWrapper.tsx ***!
  \*************************************************************/
/*! exports provided: ReactProfileWrapper, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReactProfileWrapper", function() { return ReactProfileWrapper; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_UserProvider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/UserProvider */ "./public/app/core/utils/UserProvider.tsx");
/* harmony import */ var _UserProfileEditForm__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./UserProfileEditForm */ "./public/app/features/profile/UserProfileEditForm.tsx");
/* harmony import */ var app_core_components_SharedPreferences_SharedPreferences__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/components/SharedPreferences/SharedPreferences */ "./public/app/core/components/SharedPreferences/SharedPreferences.tsx");
/* harmony import */ var _UserTeams__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./UserTeams */ "./public/app/features/profile/UserTeams.tsx");
/* harmony import */ var _UserOrganizations__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./UserOrganizations */ "./public/app/features/profile/UserOrganizations.tsx");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");








var ReactProfileWrapper = function () { return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(app_core_utils_UserProvider__WEBPACK_IMPORTED_MODULE_1__["UserProvider"], { userId: _grafana_runtime__WEBPACK_IMPORTED_MODULE_6__["config"].bootData.user.id }, function (api, states, teams, orgs, user) {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
        states.loadUser ? (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_7__["LoadingPlaceholder"], { text: "Loading user profile..." })) : (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_UserProfileEditForm__WEBPACK_IMPORTED_MODULE_2__["UserProfileEditForm"], { updateProfile: api.updateUserProfile, isSavingUser: states.updateUserProfile, user: user })),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(app_core_components_SharedPreferences_SharedPreferences__WEBPACK_IMPORTED_MODULE_3__["SharedPreferences"], { resourceUri: "user" }),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_UserTeams__WEBPACK_IMPORTED_MODULE_4__["UserTeams"], { isLoading: states.loadTeams, loadTeams: api.loadTeams, teams: teams }),
        !states.loadUser && (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_UserOrganizations__WEBPACK_IMPORTED_MODULE_5__["UserOrganizations"], { isLoading: states.loadOrgs, setUserOrg: api.setUserOrg, loadOrgs: api.loadOrgs, orgs: orgs, user: user }))));
})); };
/* harmony default export */ __webpack_exports__["default"] = (ReactProfileWrapper);


/***/ }),

/***/ "./public/app/features/profile/UserOrganizations.tsx":
/*!***********************************************************!*\
  !*** ./public/app/features/profile/UserOrganizations.tsx ***!
  \***********************************************************/
/*! exports provided: UserOrganizations, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserOrganizations", function() { return UserOrganizations; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");



var UserOrganizations = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UserOrganizations, _super);
    function UserOrganizations() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    UserOrganizations.prototype.componentDidMount = function () {
        this.props.loadOrgs();
    };
    UserOrganizations.prototype.render = function () {
        var _this = this;
        var _a = this.props, isLoading = _a.isLoading, orgs = _a.orgs, user = _a.user;
        if (isLoading) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["LoadingPlaceholder"], { text: "Loading organizations..." });
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, orgs.length > 0 && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "page-sub-heading" }, "Organizations"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("table", { className: "filter-table form-inline" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("thead", null,
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null, "Name"),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null, "Role"),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tbody", null, orgs.map(function (org, index) {
                        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { key: index },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, org.name),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, org.role),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { className: "text-right" }, org.orgId === user.orgId ? (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "btn btn-primary btn-small" }, "Current")) : (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Button"], { variant: "inverse", size: "sm", onClick: function () {
                                    _this.props.setUserOrg(org);
                                } }, "Select")))));
                    }))))))));
    };
    return UserOrganizations;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (UserOrganizations);


/***/ }),

/***/ "./public/app/features/profile/UserProfileEditForm.tsx":
/*!*************************************************************!*\
  !*** ./public/app/features/profile/UserProfileEditForm.tsx ***!
  \*************************************************************/
/*! exports provided: UserProfileEditForm, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserProfileEditForm", function() { return UserProfileEditForm; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");




var UserProfileEditForm = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UserProfileEditForm, _super);
    function UserProfileEditForm(props) {
        var _this = _super.call(this, props) || this;
        _this.onNameChange = function (event) {
            _this.setState({ name: event.target.value });
        };
        _this.onEmailChange = function (event) {
            _this.setState({ email: event.target.value });
        };
        _this.onLoginChange = function (event) {
            _this.setState({ login: event.target.value });
        };
        _this.onSubmitProfileUpdate = function (event) {
            event.preventDefault();
            _this.props.updateProfile(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.state));
        };
        var _a = _this.props.user, name = _a.name, email = _a.email, login = _a.login;
        _this.state = {
            name: name,
            email: email,
            login: login,
        };
        return _this;
    }
    UserProfileEditForm.prototype.render = function () {
        var _a = this.state, name = _a.name, email = _a.email, login = _a.login;
        var isSavingUser = this.props.isSavingUser;
        var disableLoginForm = app_core_config__WEBPACK_IMPORTED_MODULE_3__["default"].disableLoginForm;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "page-sub-heading" }, "Edit Profile"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", { name: "userForm", className: "gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form max-width-30" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { className: "width-8" }, "Name"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input max-width-22", type: "text", onChange: this.onNameChange, value: name })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form max-width-30" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { className: "width-8" }, "Email"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input max-width-22", type: "text", onChange: this.onEmailChange, value: email, disabled: disableLoginForm }),
                    disableLoginForm && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Tooltip"], { content: "Login Details Locked - managed in another system." },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-lock gf-form-icon--right-absolute" })))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form max-width-30" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { className: "width-8" }, "Username"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input max-width-22", type: "text", onChange: this.onLoginChange, value: login, disabled: disableLoginForm }),
                    disableLoginForm && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Tooltip"], { content: "Login Details Locked - managed in another system." },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-lock gf-form-icon--right-absolute" })))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-button-row" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Button"], { variant: "primary", onClick: this.onSubmitProfileUpdate, disabled: isSavingUser }, "Save")))));
    };
    return UserProfileEditForm;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (UserProfileEditForm);


/***/ }),

/***/ "./public/app/features/profile/UserTeams.tsx":
/*!***************************************************!*\
  !*** ./public/app/features/profile/UserTeams.tsx ***!
  \***************************************************/
/*! exports provided: UserTeams, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UserTeams", function() { return UserTeams; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");



var UserTeams = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UserTeams, _super);
    function UserTeams() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    UserTeams.prototype.componentDidMount = function () {
        this.props.loadTeams();
    };
    UserTeams.prototype.render = function () {
        var _a = this.props, isLoading = _a.isLoading, teams = _a.teams;
        if (isLoading) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["LoadingPlaceholder"], { text: "Loading teams..." });
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, teams.length > 0 && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", { className: "page-sub-heading" }, "Teams"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("table", { className: "filter-table form-inline" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("thead", null,
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null, "Name"),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null, "Email"),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("th", null, "Members"))),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tbody", null, teams.map(function (team, index) {
                        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { key: index },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { className: "width-4 text-center" },
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { className: "filter-table__avatar", src: team.avatarUrl })),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, team.name),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, team.email),
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, team.memberCount)));
                    }))))))));
    };
    return UserTeams;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (UserTeams);


/***/ }),

/***/ "./public/app/features/profile/all.ts":
/*!********************************************!*\
  !*** ./public/app/features/profile/all.ts ***!
  \********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ProfileCtrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ProfileCtrl */ "./public/app/features/profile/ProfileCtrl.ts");



/***/ }),

/***/ "./public/app/features/profile/state/reducers.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/profile/state/reducers.ts ***!
  \*******************************************************/
/*! exports provided: initialState, userReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "userReducer", function() { return userReducer; });
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");

var initialState = {
    orgId: app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData.user.orgId,
    timeZone: app_core_config__WEBPACK_IMPORTED_MODULE_0__["default"].bootData.user.timezone,
};
var userReducer = function (state, action) {
    if (state === void 0) { state = initialState; }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    user: userReducer,
});


/***/ }),

/***/ "./public/app/features/teams/CreateTeamCtrl.ts":
/*!*****************************************************!*\
  !*** ./public/app/features/teams/CreateTeamCtrl.ts ***!
  \*****************************************************/
/*! exports provided: CreateTeamCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateTeamCtrl", function() { return CreateTeamCtrl; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");

var CreateTeamCtrl = /** @class */ (function () {
    /** @ngInject */
    function CreateTeamCtrl(backendSrv, $location, navModelSrv) {
        this.backendSrv = backendSrv;
        this.$location = $location;
        this.navModel = navModelSrv.getNav('cfg', 'teams', 0);
    }
    CreateTeamCtrl.prototype.create = function () {
        var _this = this;
        var payload = {
            name: this.name,
            email: this.email,
        };
        this.backendSrv.post('/api/teams', payload).then(function (result) {
            if (result.teamId) {
                _this.$location.path('/org/teams/edit/' + result.teamId);
            }
        });
    };
    return CreateTeamCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].controller('CreateTeamCtrl', CreateTeamCtrl);


/***/ }),

/***/ "./public/app/features/teams/state/actions.ts":
/*!****************************************************!*\
  !*** ./public/app/features/teams/state/actions.ts ***!
  \****************************************************/
/*! exports provided: ActionTypes, setSearchMemberQuery, setSearchQuery, loadTeams, loadTeam, loadTeamMembers, addTeamMember, removeTeamMember, updateTeam, loadTeamGroups, addTeamGroup, removeTeamGroup, deleteTeam, updateTeamMember */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSearchMemberQuery", function() { return setSearchMemberQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSearchQuery", function() { return setSearchQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadTeams", function() { return loadTeams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadTeam", function() { return loadTeam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadTeamMembers", function() { return loadTeamMembers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addTeamMember", function() { return addTeamMember; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeTeamMember", function() { return removeTeamMember; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTeam", function() { return updateTeam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadTeamGroups", function() { return loadTeamGroups; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addTeamGroup", function() { return addTeamGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeTeamGroup", function() { return removeTeamGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteTeam", function() { return deleteTeam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTeamMember", function() { return updateTeamMember; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var _navModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./navModel */ "./public/app/features/teams/state/navModel.ts");




var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadTeams"] = "LOAD_TEAMS";
    ActionTypes["LoadTeam"] = "LOAD_TEAM";
    ActionTypes["SetSearchQuery"] = "SET_TEAM_SEARCH_QUERY";
    ActionTypes["SetSearchMemberQuery"] = "SET_TEAM_MEMBER_SEARCH_QUERY";
    ActionTypes["LoadTeamMembers"] = "TEAM_MEMBERS_LOADED";
    ActionTypes["LoadTeamGroups"] = "TEAM_GROUPS_LOADED";
})(ActionTypes || (ActionTypes = {}));
var teamsLoaded = function (teams) { return ({
    type: ActionTypes.LoadTeams,
    payload: teams,
}); };
var teamLoaded = function (team) { return ({
    type: ActionTypes.LoadTeam,
    payload: team,
}); };
var teamMembersLoaded = function (teamMembers) { return ({
    type: ActionTypes.LoadTeamMembers,
    payload: teamMembers,
}); };
var teamGroupsLoaded = function (teamGroups) { return ({
    type: ActionTypes.LoadTeamGroups,
    payload: teamGroups,
}); };
var setSearchMemberQuery = function (searchQuery) { return ({
    type: ActionTypes.SetSearchMemberQuery,
    payload: searchQuery,
}); };
var setSearchQuery = function (searchQuery) { return ({
    type: ActionTypes.SetSearchQuery,
    payload: searchQuery,
}); };
function loadTeams() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/teams/search', { perpage: 1000, page: 1 })];
                case 1:
                    response = _a.sent();
                    dispatch(teamsLoaded(response.teams));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadTeam(id) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/teams/" + id)];
                case 1:
                    response = _a.sent();
                    dispatch(teamLoaded(response));
                    dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_2__["updateNavIndex"])(Object(_navModel__WEBPACK_IMPORTED_MODULE_3__["buildNavModel"])(response)));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadTeamMembers() {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team, response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/teams/" + team.id + "/members")];
                case 1:
                    response = _a.sent();
                    dispatch(teamMembersLoaded(response));
                    return [2 /*return*/];
            }
        });
    }); };
}
function addTeamMember(id) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/teams/" + team.id + "/members", { userId: id })];
                case 1:
                    _a.sent();
                    dispatch(loadTeamMembers());
                    return [2 /*return*/];
            }
        });
    }); };
}
function removeTeamMember(id) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().delete("/api/teams/" + team.id + "/members/" + id)];
                case 1:
                    _a.sent();
                    dispatch(loadTeamMembers());
                    return [2 /*return*/];
            }
        });
    }); };
}
function updateTeam(name, email) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().put("/api/teams/" + team.id, { name: name, email: email })];
                case 1:
                    _a.sent();
                    dispatch(loadTeam(team.id));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadTeamGroups() {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team, response;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get("/api/teams/" + team.id + "/groups")];
                case 1:
                    response = _a.sent();
                    dispatch(teamGroupsLoaded(response));
                    return [2 /*return*/];
            }
        });
    }); };
}
function addTeamGroup(groupId) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().post("/api/teams/" + team.id + "/groups", { groupId: groupId })];
                case 1:
                    _a.sent();
                    dispatch(loadTeamGroups());
                    return [2 /*return*/];
            }
        });
    }); };
}
function removeTeamGroup(groupId) {
    var _this = this;
    return function (dispatch, getStore) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var team;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    team = getStore().team.team;
                    return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().delete("/api/teams/" + team.id + "/groups/" + groupId)];
                case 1:
                    _a.sent();
                    dispatch(loadTeamGroups());
                    return [2 /*return*/];
            }
        });
    }); };
}
function deleteTeam(id) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().delete("/api/teams/" + id)];
                case 1:
                    _a.sent();
                    dispatch(loadTeams());
                    return [2 /*return*/];
            }
        });
    }); };
}
function updateTeamMember(member) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().put("/api/teams/" + member.teamId + "/members/" + member.userId, {
                        permission: member.permission,
                    })];
                case 1:
                    _a.sent();
                    dispatch(loadTeamMembers());
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/teams/state/navModel.ts":
/*!*****************************************************!*\
  !*** ./public/app/features/teams/state/navModel.ts ***!
  \*****************************************************/
/*! exports provided: buildNavModel, getTeamLoadingNav */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildNavModel", function() { return buildNavModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTeamLoadingNav", function() { return getTeamLoadingNav; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



function buildNavModel(team) {
    var navModel = {
        img: team.avatarUrl,
        id: 'team-' + team.id,
        subTitle: 'Manage members & settings',
        url: '',
        text: team.name,
        breadcrumbs: [{ title: 'Teams', url: 'org/teams' }],
        children: [
            {
                active: false,
                icon: 'gicon gicon-team',
                id: "team-members-" + team.id,
                text: 'Members',
                url: "org/teams/edit/" + team.id + "/members",
            },
            {
                active: false,
                icon: 'fa fa-fw fa-sliders',
                id: "team-settings-" + team.id,
                text: 'Settings',
                url: "org/teams/edit/" + team.id + "/settings",
            },
        ],
    };
    if (app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].buildInfo.isEnterprise) {
        navModel.children.push({
            active: false,
            icon: 'fa fa-fw fa-refresh',
            id: "team-groupsync-" + team.id,
            text: 'External group sync',
            url: "org/teams/edit/" + team.id + "/groupsync",
        });
    }
    return navModel;
}
function getTeamLoadingNav(pageName) {
    var e_1, _a;
    var main = buildNavModel({
        avatarUrl: 'public/img/user_profile.png',
        id: 1,
        name: 'Loading',
        email: 'loading',
        memberCount: 0,
        permission: app_types__WEBPACK_IMPORTED_MODULE_1__["TeamPermissionLevel"].Member,
    });
    var node;
    try {
        // find active page
        for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](main.children), _c = _b.next(); !_c.done; _c = _b.next()) {
            var child = _c.value;
            if (child.id.indexOf(pageName) > 0) {
                child.active = true;
                node = child;
                break;
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return {
        main: main,
        node: node,
    };
}


/***/ }),

/***/ "./public/app/features/teams/state/reducers.ts":
/*!*****************************************************!*\
  !*** ./public/app/features/teams/state/reducers.ts ***!
  \*****************************************************/
/*! exports provided: initialTeamsState, initialTeamState, teamsReducer, teamReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialTeamsState", function() { return initialTeamsState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialTeamState", function() { return initialTeamState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "teamsReducer", function() { return teamsReducer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "teamReducer", function() { return teamReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/teams/state/actions.ts");


var initialTeamsState = { teams: [], searchQuery: '', hasFetched: false };
var initialTeamState = {
    team: {},
    members: [],
    groups: [],
    searchMemberQuery: '',
};
var teamsReducer = function (state, action) {
    if (state === void 0) { state = initialTeamsState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadTeams:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hasFetched: true, teams: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetSearchQuery:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchQuery: action.payload });
    }
    return state;
};
var teamReducer = function (state, action) {
    if (state === void 0) { state = initialTeamState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadTeam:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { team: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadTeamMembers:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { members: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetSearchMemberQuery:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchMemberQuery: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadTeamGroups:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { groups: action.payload });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    teams: teamsReducer,
    team: teamReducer,
});


/***/ }),

/***/ "./public/app/features/templating/DefaultVariableQueryEditor.tsx":
/*!***********************************************************************!*\
  !*** ./public/app/features/templating/DefaultVariableQueryEditor.tsx ***!
  \***********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");



var DefaultVariableQueryEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DefaultVariableQueryEditor, _super);
    function DefaultVariableQueryEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.onChange = function (event) {
            _this.setState({ value: event.currentTarget.value });
        };
        _this.onBlur = function (event) {
            _this.props.onChange(event.currentTarget.value, event.currentTarget.value);
        };
        _this.state = { value: props.query };
        return _this;
    }
    DefaultVariableQueryEditor.prototype.render = function () {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label width-10" }, "Query"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { type: "text", className: "gf-form-input", value: this.state.value, onChange: this.onChange, onBlur: this.onBlur, placeholder: "metric name or tags query", required: true })));
    };
    return DefaultVariableQueryEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
/* harmony default export */ __webpack_exports__["default"] = (DefaultVariableQueryEditor);


/***/ }),

/***/ "./public/app/features/templating/TextBoxVariable.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/templating/TextBoxVariable.ts ***!
  \***********************************************************/
/*! exports provided: TextBoxVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextBoxVariable", function() { return TextBoxVariable; });
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");

var TextBoxVariable = /** @class */ (function () {
    /** @ngInject */
    function TextBoxVariable(model, variableSrv) {
        this.model = model;
        this.variableSrv = variableSrv;
        this.defaults = {
            type: 'textbox',
            name: '',
            hide: 0,
            label: '',
            query: '',
            current: {},
            options: [],
            skipUrlSync: false,
        };
        Object(_variable__WEBPACK_IMPORTED_MODULE_0__["assignModelProperties"])(this, model, this.defaults);
    }
    TextBoxVariable.prototype.getSaveModel = function () {
        Object(_variable__WEBPACK_IMPORTED_MODULE_0__["assignModelProperties"])(this.model, this, this.defaults);
        return this.model;
    };
    TextBoxVariable.prototype.setValue = function (option) {
        this.variableSrv.setOptionAsCurrent(this, option);
    };
    TextBoxVariable.prototype.updateOptions = function () {
        this.options = [{ text: this.query.trim(), value: this.query.trim() }];
        this.current = this.options[0];
        return Promise.resolve();
    };
    TextBoxVariable.prototype.dependsOn = function (variable) {
        return false;
    };
    TextBoxVariable.prototype.setValueFromUrl = function (urlValue) {
        this.query = urlValue;
        return this.variableSrv.setOptionFromUrl(this, urlValue);
    };
    TextBoxVariable.prototype.getValueForUrl = function () {
        return this.current.value;
    };
    return TextBoxVariable;
}());

// @ts-ignore
_variable__WEBPACK_IMPORTED_MODULE_0__["variableTypes"]['textbox'] = {
    name: 'Text box',
    ctor: TextBoxVariable,
    description: 'Define a textbox variable, where users can enter any arbitrary string',
};


/***/ }),

/***/ "./public/app/features/templating/adhoc_variable.ts":
/*!**********************************************************!*\
  !*** ./public/app/features/templating/adhoc_variable.ts ***!
  \**********************************************************/
/*! exports provided: AdhocVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdhocVariable", function() { return AdhocVariable; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");


var AdhocVariable = /** @class */ (function () {
    /** @ngInject */
    function AdhocVariable(model) {
        this.model = model;
        this.defaults = {
            type: 'adhoc',
            name: '',
            label: '',
            hide: 0,
            datasource: null,
            filters: [],
            skipUrlSync: false,
        };
        Object(_variable__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"])(this, model, this.defaults);
    }
    AdhocVariable.prototype.setValue = function (option) {
        return Promise.resolve();
    };
    AdhocVariable.prototype.getSaveModel = function () {
        Object(_variable__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"])(this.model, this, this.defaults);
        return this.model;
    };
    AdhocVariable.prototype.updateOptions = function () {
        return Promise.resolve();
    };
    AdhocVariable.prototype.dependsOn = function (variable) {
        return false;
    };
    AdhocVariable.prototype.setValueFromUrl = function (urlValue) {
        var _this = this;
        if (!lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(urlValue)) {
            urlValue = [urlValue];
        }
        this.filters = urlValue.map(function (item) {
            var values = item.split('|').map(function (value) {
                return _this.unescapeDelimiter(value);
            });
            return {
                key: values[0],
                operator: values[1],
                value: values[2],
            };
        });
        return Promise.resolve();
    };
    AdhocVariable.prototype.getValueForUrl = function () {
        var _this = this;
        return this.filters.map(function (filter) {
            return [filter.key, filter.operator, filter.value]
                .map(function (value) {
                return _this.escapeDelimiter(value);
            })
                .join('|');
        });
    };
    AdhocVariable.prototype.escapeDelimiter = function (value) {
        return value.replace(/\|/g, '__gfp__');
    };
    AdhocVariable.prototype.unescapeDelimiter = function (value) {
        return value.replace(/__gfp__/g, '|');
    };
    AdhocVariable.prototype.setFilters = function (filters) {
        this.filters = filters;
    };
    return AdhocVariable;
}());

_variable__WEBPACK_IMPORTED_MODULE_1__["variableTypes"]['adhoc'] = {
    name: 'Ad hoc filters',
    ctor: AdhocVariable,
    description: 'Add key/value filters on the fly',
};


/***/ }),

/***/ "./public/app/features/templating/all.ts":
/*!***********************************************!*\
  !*** ./public/app/features/templating/all.ts ***!
  \***********************************************/
/*! exports provided: VariableSrv, IntervalVariable, QueryVariable, DatasourceVariable, CustomVariable, ConstantVariable, AdhocVariable, TextBoxVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _editor_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./editor_ctrl */ "./public/app/features/templating/editor_ctrl.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _template_srv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./template_srv */ "./public/app/features/templating/template_srv.ts");
/* harmony import */ var _variable_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./variable_srv */ "./public/app/features/templating/variable_srv.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VariableSrv", function() { return _variable_srv__WEBPACK_IMPORTED_MODULE_3__["VariableSrv"]; });

/* harmony import */ var _interval_variable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./interval_variable */ "./public/app/features/templating/interval_variable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntervalVariable", function() { return _interval_variable__WEBPACK_IMPORTED_MODULE_4__["IntervalVariable"]; });

/* harmony import */ var _query_variable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./query_variable */ "./public/app/features/templating/query_variable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QueryVariable", function() { return _query_variable__WEBPACK_IMPORTED_MODULE_5__["QueryVariable"]; });

/* harmony import */ var _datasource_variable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./datasource_variable */ "./public/app/features/templating/datasource_variable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DatasourceVariable", function() { return _datasource_variable__WEBPACK_IMPORTED_MODULE_6__["DatasourceVariable"]; });

/* harmony import */ var _custom_variable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./custom_variable */ "./public/app/features/templating/custom_variable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomVariable", function() { return _custom_variable__WEBPACK_IMPORTED_MODULE_7__["CustomVariable"]; });

/* harmony import */ var _constant_variable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./constant_variable */ "./public/app/features/templating/constant_variable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConstantVariable", function() { return _constant_variable__WEBPACK_IMPORTED_MODULE_8__["ConstantVariable"]; });

/* harmony import */ var _adhoc_variable__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./adhoc_variable */ "./public/app/features/templating/adhoc_variable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AdhocVariable", function() { return _adhoc_variable__WEBPACK_IMPORTED_MODULE_9__["AdhocVariable"]; });

/* harmony import */ var _TextBoxVariable__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./TextBoxVariable */ "./public/app/features/templating/TextBoxVariable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextBoxVariable", function() { return _TextBoxVariable__WEBPACK_IMPORTED_MODULE_10__["TextBoxVariable"]; });












app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].factory('templateSrv', function () {
    return _template_srv__WEBPACK_IMPORTED_MODULE_2__["default"];
});



/***/ }),

/***/ "./public/app/features/templating/constant_variable.ts":
/*!*************************************************************!*\
  !*** ./public/app/features/templating/constant_variable.ts ***!
  \*************************************************************/
/*! exports provided: ConstantVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConstantVariable", function() { return ConstantVariable; });
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");

var ConstantVariable = /** @class */ (function () {
    /** @ngInject */
    function ConstantVariable(model, variableSrv) {
        this.model = model;
        this.variableSrv = variableSrv;
        this.defaults = {
            type: 'constant',
            name: '',
            hide: 2,
            label: '',
            query: '',
            current: {},
            options: [],
            skipUrlSync: false,
        };
        Object(_variable__WEBPACK_IMPORTED_MODULE_0__["assignModelProperties"])(this, model, this.defaults);
    }
    ConstantVariable.prototype.getSaveModel = function () {
        Object(_variable__WEBPACK_IMPORTED_MODULE_0__["assignModelProperties"])(this.model, this, this.defaults);
        return this.model;
    };
    ConstantVariable.prototype.setValue = function (option) {
        this.variableSrv.setOptionAsCurrent(this, option);
    };
    ConstantVariable.prototype.updateOptions = function () {
        this.options = [{ text: this.query.trim(), value: this.query.trim() }];
        this.setValue(this.options[0]);
        return Promise.resolve();
    };
    ConstantVariable.prototype.dependsOn = function (variable) {
        return false;
    };
    ConstantVariable.prototype.setValueFromUrl = function (urlValue) {
        return this.variableSrv.setOptionFromUrl(this, urlValue);
    };
    ConstantVariable.prototype.getValueForUrl = function () {
        return this.current.value;
    };
    return ConstantVariable;
}());

_variable__WEBPACK_IMPORTED_MODULE_0__["variableTypes"]['constant'] = {
    name: 'Constant',
    ctor: ConstantVariable,
    description: 'Define a hidden constant variable, useful for metric prefixes in dashboards you want to share',
};


/***/ }),

/***/ "./public/app/features/templating/custom_variable.ts":
/*!***********************************************************!*\
  !*** ./public/app/features/templating/custom_variable.ts ***!
  \***********************************************************/
/*! exports provided: CustomVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomVariable", function() { return CustomVariable; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");


var CustomVariable = /** @class */ (function () {
    /** @ngInject */
    function CustomVariable(model, variableSrv) {
        this.model = model;
        this.variableSrv = variableSrv;
        this.defaults = {
            type: 'custom',
            name: '',
            label: '',
            hide: 0,
            options: [],
            current: {},
            query: '',
            includeAll: false,
            multi: false,
            allValue: null,
            skipUrlSync: false,
        };
        Object(_variable__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"])(this, model, this.defaults);
    }
    CustomVariable.prototype.setValue = function (option) {
        return this.variableSrv.setOptionAsCurrent(this, option);
    };
    CustomVariable.prototype.getSaveModel = function () {
        Object(_variable__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"])(this.model, this, this.defaults);
        return this.model;
    };
    CustomVariable.prototype.updateOptions = function () {
        // extract options in comma separated string (use backslash to escape wanted commas)
        this.options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(this.query.match(/(?:\\,|[^,])+/g), function (text) {
            text = text.replace(/\\,/g, ',');
            return { text: text.trim(), value: text.trim() };
        });
        if (this.includeAll) {
            this.addAllOption();
        }
        return this.variableSrv.validateVariableSelectionState(this);
    };
    CustomVariable.prototype.addAllOption = function () {
        this.options.unshift({ text: 'All', value: '$__all' });
    };
    CustomVariable.prototype.dependsOn = function (variable) {
        return false;
    };
    CustomVariable.prototype.setValueFromUrl = function (urlValue) {
        return this.variableSrv.setOptionFromUrl(this, urlValue);
    };
    CustomVariable.prototype.getValueForUrl = function () {
        if (this.current.text === 'All') {
            return 'All';
        }
        return this.current.value;
    };
    return CustomVariable;
}());

_variable__WEBPACK_IMPORTED_MODULE_1__["variableTypes"]['custom'] = {
    name: 'Custom',
    ctor: CustomVariable,
    description: 'Define variable values manually',
    supportsMulti: true,
};


/***/ }),

/***/ "./public/app/features/templating/datasource_variable.ts":
/*!***************************************************************!*\
  !*** ./public/app/features/templating/datasource_variable.ts ***!
  \***************************************************************/
/*! exports provided: DatasourceVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DatasourceVariable", function() { return DatasourceVariable; });
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");


var DatasourceVariable = /** @class */ (function () {
    /** @ngInject */
    function DatasourceVariable(model, datasourceSrv, variableSrv, templateSrv) {
        this.model = model;
        this.datasourceSrv = datasourceSrv;
        this.variableSrv = variableSrv;
        this.templateSrv = templateSrv;
        this.defaults = {
            type: 'datasource',
            name: '',
            hide: 0,
            label: '',
            current: {},
            regex: '',
            options: [],
            query: '',
            multi: false,
            includeAll: false,
            refresh: 1,
            skipUrlSync: false,
        };
        Object(_variable__WEBPACK_IMPORTED_MODULE_0__["assignModelProperties"])(this, model, this.defaults);
        this.refresh = 1;
    }
    DatasourceVariable.prototype.getSaveModel = function () {
        Object(_variable__WEBPACK_IMPORTED_MODULE_0__["assignModelProperties"])(this.model, this, this.defaults);
        // don't persist options
        this.model.options = [];
        return this.model;
    };
    DatasourceVariable.prototype.setValue = function (option) {
        return this.variableSrv.setOptionAsCurrent(this, option);
    };
    DatasourceVariable.prototype.updateOptions = function () {
        var options = [];
        var sources = this.datasourceSrv.getMetricSources({ skipVariables: true });
        var regex;
        if (this.regex) {
            regex = this.templateSrv.replace(this.regex, null, 'regex');
            regex = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_1__["stringToJsRegex"])(regex);
        }
        for (var i = 0; i < sources.length; i++) {
            var source = sources[i];
            // must match on type
            if (source.meta.id !== this.query) {
                continue;
            }
            if (regex && !regex.exec(source.name)) {
                continue;
            }
            options.push({ text: source.name, value: source.name });
        }
        if (options.length === 0) {
            options.push({ text: 'No data sources found', value: '' });
        }
        this.options = options;
        if (this.includeAll) {
            this.addAllOption();
        }
        return this.variableSrv.validateVariableSelectionState(this);
    };
    DatasourceVariable.prototype.addAllOption = function () {
        this.options.unshift({ text: 'All', value: '$__all' });
    };
    DatasourceVariable.prototype.dependsOn = function (variable) {
        if (this.regex) {
            return Object(_variable__WEBPACK_IMPORTED_MODULE_0__["containsVariable"])(this.regex, variable.name);
        }
        return false;
    };
    DatasourceVariable.prototype.setValueFromUrl = function (urlValue) {
        return this.variableSrv.setOptionFromUrl(this, urlValue);
    };
    DatasourceVariable.prototype.getValueForUrl = function () {
        if (this.current.text === 'All') {
            return 'All';
        }
        return this.current.value;
    };
    return DatasourceVariable;
}());

_variable__WEBPACK_IMPORTED_MODULE_0__["variableTypes"]['datasource'] = {
    name: 'Datasource',
    ctor: DatasourceVariable,
    supportsMulti: true,
    description: 'Enabled you to dynamically switch the datasource for multiple panels',
};


/***/ }),

/***/ "./public/app/features/templating/editor_ctrl.ts":
/*!*******************************************************!*\
  !*** ./public/app/features/templating/editor_ctrl.ts ***!
  \*******************************************************/
/*! exports provided: VariableEditorCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VariableEditorCtrl", function() { return VariableEditorCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");





var VariableEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function VariableEditorCtrl($scope, datasourceSrv, variableSrv, templateSrv) {
        var _this = this;
        $scope.variableTypes = _variable__WEBPACK_IMPORTED_MODULE_3__["variableTypes"];
        $scope.ctrl = {};
        $scope.namePattern = /^(?!__).*$/;
        $scope._ = lodash__WEBPACK_IMPORTED_MODULE_1___default.a;
        $scope.optionsLimit = 20;
        $scope.emptyListCta = {
            title: 'There are no variables yet',
            buttonTitle: 'Add variable',
            buttonIcon: 'gicon gicon-variable',
            infoBox: {
                __html: " <p>\n      Variables enable more interactive and dynamic dashboards. Instead of hard-coding things like server or\n      sensor names in your metric queries you can use variables in their place. Variables are shown as dropdown\n      select boxes at the top of the dashboard. These dropdowns make it easy to change the data being displayed in\n      your dashboard. Check out the\n      <a class=\"external-link\" href=\"http://docs.grafana.org/reference/templating/\" target=\"_blank\">\n        Templating documentation\n      </a>\n      for more information.\n    </p>",
                infoBoxTitle: 'What do variables do?',
            },
        };
        $scope.refreshOptions = [
            { value: 0, text: 'Never' },
            { value: 1, text: 'On Dashboard Load' },
            { value: 2, text: 'On Time Range Change' },
        ];
        $scope.sortOptions = [
            { value: 0, text: 'Disabled' },
            { value: 1, text: 'Alphabetical (asc)' },
            { value: 2, text: 'Alphabetical (desc)' },
            { value: 3, text: 'Numerical (asc)' },
            { value: 4, text: 'Numerical (desc)' },
            { value: 5, text: 'Alphabetical (case-insensitive, asc)' },
            { value: 6, text: 'Alphabetical (case-insensitive, desc)' },
        ];
        $scope.hideOptions = [{ value: 0, text: '' }, { value: 1, text: 'Label' }, { value: 2, text: 'Variable' }];
        $scope.init = function () {
            $scope.mode = 'list';
            $scope.variables = variableSrv.variables;
            $scope.reset();
            $scope.$watch('mode', function (val) {
                if (val === 'new') {
                    $scope.reset();
                }
            });
        };
        $scope.setMode = function (mode) {
            $scope.mode = mode;
        };
        $scope.setNewMode = function () {
            $scope.setMode('new');
        };
        $scope.add = function () {
            if ($scope.isValid()) {
                variableSrv.addVariable($scope.current);
                $scope.update();
            }
        };
        $scope.isValid = function () {
            if (!$scope.ctrl.form.$valid) {
                return false;
            }
            if (!$scope.current.name.match(/^\w+$/)) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('alert-warning', ['Validation', 'Only word and digit characters are allowed in variable names']);
                return false;
            }
            var sameName = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find($scope.variables, { name: $scope.current.name });
            if (sameName && sameName !== $scope.current) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('alert-warning', ['Validation', 'Variable with the same name already exists']);
                return false;
            }
            if ($scope.current.type === 'query' &&
                lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isString($scope.current.query) &&
                $scope.current.query.match(new RegExp('\\$' + $scope.current.name + '(/| |$)'))) {
                app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('alert-warning', [
                    'Validation',
                    'Query cannot contain a reference to itself. Variable: $' + $scope.current.name,
                ]);
                return false;
            }
            return true;
        };
        $scope.validate = function () {
            $scope.infoText = '';
            if ($scope.current.type === 'adhoc' && $scope.current.datasource !== null) {
                $scope.infoText = 'Adhoc filters are applied automatically to all queries that target this datasource';
                datasourceSrv.get($scope.current.datasource).then(function (ds) {
                    if (!ds.getTagKeys) {
                        $scope.infoText = 'This datasource does not support adhoc filters yet.';
                    }
                });
            }
        };
        $scope.runQuery = function () {
            $scope.optionsLimit = 20;
            return variableSrv.updateOptions($scope.current).catch(function (err) {
                if (err.data && err.data.message) {
                    err.message = err.data.message;
                }
                app_core_app_events__WEBPACK_IMPORTED_MODULE_4__["default"].emit('alert-error', ['Templating', 'Template variables could not be initialized: ' + err.message]);
            });
        };
        $scope.onQueryChange = function (query, definition) {
            $scope.current.query = query;
            $scope.current.definition = definition;
            $scope.runQuery();
        };
        $scope.edit = function (variable) {
            $scope.current = variable;
            $scope.currentIsNew = false;
            $scope.mode = 'edit';
            $scope.validate();
            datasourceSrv.get($scope.current.datasource).then(function (ds) {
                $scope.currentDatasource = ds;
            });
        };
        $scope.duplicate = function (variable) {
            var clone = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.cloneDeep(variable.getSaveModel());
            $scope.current = variableSrv.createVariableFromModel(clone);
            $scope.current.name = 'copy_of_' + variable.name;
            variableSrv.addVariable($scope.current);
        };
        $scope.update = function () {
            if ($scope.isValid()) {
                $scope.runQuery().then(function () {
                    $scope.reset();
                    $scope.mode = 'list';
                    templateSrv.updateIndex();
                });
            }
        };
        $scope.reset = function () {
            $scope.currentIsNew = true;
            $scope.current = variableSrv.createVariableFromModel({ type: 'query' });
            // this is done here in case a new data source type variable was added
            $scope.datasources = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(datasourceSrv.getMetricSources(), function (ds) {
                return !ds.meta.mixed && ds.value !== null;
            });
            $scope.datasourceTypes = lodash__WEBPACK_IMPORTED_MODULE_1___default()($scope.datasources)
                .uniqBy('meta.id')
                .map(function (ds) {
                return { text: ds.meta.name, value: ds.meta.id };
            })
                .value();
        };
        $scope.typeChanged = function () {
            var old = $scope.current;
            $scope.current = variableSrv.createVariableFromModel({
                type: $scope.current.type,
            });
            $scope.current.name = old.name;
            $scope.current.label = old.label;
            var oldIndex = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.variables, old);
            if (oldIndex !== -1) {
                this.variables[oldIndex] = $scope.current;
            }
            $scope.validate();
        };
        $scope.removeVariable = function (variable) {
            variableSrv.removeVariable(variable);
        };
        $scope.showMoreOptions = function () {
            $scope.optionsLimit += 20;
        };
        $scope.datasourceChanged = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                datasourceSrv.get($scope.current.datasource).then(function (ds) {
                    $scope.current.query = '';
                    $scope.currentDatasource = ds;
                });
                return [2 /*return*/];
            });
        }); };
    }
    return VariableEditorCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_2__["default"].controller('VariableEditorCtrl', VariableEditorCtrl);


/***/ }),

/***/ "./public/app/features/templating/interval_variable.ts":
/*!*************************************************************!*\
  !*** ./public/app/features/templating/interval_variable.ts ***!
  \*************************************************************/
/*! exports provided: IntervalVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntervalVariable", function() { return IntervalVariable; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");



var IntervalVariable = /** @class */ (function () {
    /** @ngInject */
    function IntervalVariable(model, timeSrv, templateSrv, variableSrv) {
        this.model = model;
        this.timeSrv = timeSrv;
        this.templateSrv = templateSrv;
        this.variableSrv = variableSrv;
        this.defaults = {
            type: 'interval',
            name: '',
            hide: 0,
            label: '',
            refresh: 2,
            options: [],
            current: {},
            query: '1m,10m,30m,1h,6h,12h,1d,7d,14d,30d',
            auto: false,
            auto_min: '10s',
            auto_count: 30,
            skipUrlSync: false,
        };
        Object(_variable__WEBPACK_IMPORTED_MODULE_2__["assignModelProperties"])(this, model, this.defaults);
        this.refresh = 2;
    }
    IntervalVariable.prototype.getSaveModel = function () {
        Object(_variable__WEBPACK_IMPORTED_MODULE_2__["assignModelProperties"])(this.model, this, this.defaults);
        return this.model;
    };
    IntervalVariable.prototype.setValue = function (option) {
        this.updateAutoValue();
        return this.variableSrv.setOptionAsCurrent(this, option);
    };
    IntervalVariable.prototype.updateAutoValue = function () {
        if (!this.auto) {
            return;
        }
        // add auto option if missing
        if (this.options.length && this.options[0].text !== 'auto') {
            this.options.unshift({
                text: 'auto',
                value: '$__auto_interval_' + this.name,
            });
        }
        var res = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__["default"].calculateInterval(this.timeSrv.timeRange(), this.auto_count, this.auto_min);
        this.templateSrv.setGrafanaVariable('$__auto_interval_' + this.name, res.interval);
        // for backward compatibility, to be removed eventually
        this.templateSrv.setGrafanaVariable('$__auto_interval', res.interval);
    };
    IntervalVariable.prototype.updateOptions = function () {
        // extract options between quotes and/or comma
        this.options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(this.query.match(/(["'])(.*?)\1|\w+/g), function (text) {
            text = text.replace(/["']+/g, '');
            return { text: text.trim(), value: text.trim() };
        });
        this.updateAutoValue();
        return this.variableSrv.validateVariableSelectionState(this);
    };
    IntervalVariable.prototype.dependsOn = function (variable) {
        return false;
    };
    IntervalVariable.prototype.setValueFromUrl = function (urlValue) {
        this.updateAutoValue();
        return this.variableSrv.setOptionFromUrl(this, urlValue);
    };
    IntervalVariable.prototype.getValueForUrl = function () {
        return this.current.value;
    };
    return IntervalVariable;
}());

// @ts-ignore
_variable__WEBPACK_IMPORTED_MODULE_2__["variableTypes"]['interval'] = {
    name: 'Interval',
    ctor: IntervalVariable,
    description: 'Define a timespan interval (ex 1m, 1h, 1d)',
};


/***/ }),

/***/ "./public/app/features/templating/query_variable.ts":
/*!**********************************************************!*\
  !*** ./public/app/features/templating/query_variable.ts ***!
  \**********************************************************/
/*! exports provided: QueryVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryVariable", function() { return QueryVariable; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");



function getNoneOption() {
    return { text: 'None', value: '', isNone: true };
}
var QueryVariable = /** @class */ (function () {
    /** @ngInject */
    function QueryVariable(model, datasourceSrv, templateSrv, variableSrv, timeSrv) {
        this.model = model;
        this.datasourceSrv = datasourceSrv;
        this.templateSrv = templateSrv;
        this.variableSrv = variableSrv;
        this.timeSrv = timeSrv;
        this.defaults = {
            type: 'query',
            label: null,
            query: '',
            regex: '',
            sort: 0,
            datasource: null,
            refresh: 0,
            hide: 0,
            name: '',
            multi: false,
            includeAll: false,
            allValue: null,
            options: [],
            current: {},
            tags: [],
            useTags: false,
            tagsQuery: '',
            tagValuesQuery: '',
            skipUrlSync: false,
            definition: '',
        };
        // copy model properties to this instance
        Object(_variable__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"])(this, model, this.defaults);
    }
    QueryVariable.prototype.getSaveModel = function () {
        // copy back model properties to model
        Object(_variable__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"])(this.model, this, this.defaults);
        // remove options
        if (this.refresh !== 0) {
            this.model.options = [];
        }
        return this.model;
    };
    QueryVariable.prototype.setValue = function (option) {
        return this.variableSrv.setOptionAsCurrent(this, option);
    };
    QueryVariable.prototype.setValueFromUrl = function (urlValue) {
        return this.variableSrv.setOptionFromUrl(this, urlValue);
    };
    QueryVariable.prototype.getValueForUrl = function () {
        if (this.current.text === 'All') {
            return 'All';
        }
        return this.current.value;
    };
    QueryVariable.prototype.updateOptions = function () {
        return this.datasourceSrv
            .get(this.datasource)
            .then(this.updateOptionsFromMetricFindQuery.bind(this))
            .then(this.updateTags.bind(this))
            .then(this.variableSrv.validateVariableSelectionState.bind(this.variableSrv, this));
    };
    QueryVariable.prototype.updateTags = function (datasource) {
        var _this = this;
        if (this.useTags) {
            return this.metricFindQuery(datasource, this.tagsQuery).then(function (results) {
                _this.tags = [];
                for (var i = 0; i < results.length; i++) {
                    _this.tags.push(results[i].text);
                }
                return datasource;
            });
        }
        else {
            delete this.tags;
        }
        return datasource;
    };
    QueryVariable.prototype.getValuesForTag = function (tagKey) {
        var _this = this;
        return this.datasourceSrv.get(this.datasource).then(function (datasource) {
            var query = _this.tagValuesQuery.replace('$tag', tagKey);
            return _this.metricFindQuery(datasource, query).then(function (results) {
                return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(results, function (value) {
                    return value.text;
                });
            });
        });
    };
    QueryVariable.prototype.updateOptionsFromMetricFindQuery = function (datasource) {
        var _this = this;
        return this.metricFindQuery(datasource, this.query).then(function (results) {
            _this.options = _this.metricNamesToVariableValues(results);
            if (_this.includeAll) {
                _this.addAllOption();
            }
            if (!_this.options.length) {
                _this.options.push(getNoneOption());
            }
            return datasource;
        });
    };
    QueryVariable.prototype.metricFindQuery = function (datasource, query) {
        var options = { range: undefined, variable: this };
        if (this.refresh === 2) {
            options.range = this.timeSrv.timeRange();
        }
        return datasource.metricFindQuery(query, options);
    };
    QueryVariable.prototype.addAllOption = function () {
        this.options.unshift({ text: 'All', value: '$__all' });
    };
    QueryVariable.prototype.metricNamesToVariableValues = function (metricNames) {
        var regex, options, i, matches;
        options = [];
        if (this.regex) {
            regex = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["stringToJsRegex"])(this.templateSrv.replace(this.regex, {}, 'regex'));
        }
        for (i = 0; i < metricNames.length; i++) {
            var item = metricNames[i];
            var text = item.text === undefined || item.text === null ? item.value : item.text;
            var value = item.value === undefined || item.value === null ? item.text : item.value;
            if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(value)) {
                value = value.toString();
            }
            if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(text)) {
                text = text.toString();
            }
            if (regex) {
                matches = regex.exec(value);
                if (!matches) {
                    continue;
                }
                if (matches.length > 1) {
                    value = matches[1];
                    text = matches[1];
                }
            }
            options.push({ text: text, value: value });
        }
        options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.uniqBy(options, 'value');
        return this.sortVariableValues(options, this.sort);
    };
    QueryVariable.prototype.sortVariableValues = function (options, sortOrder) {
        if (sortOrder === 0) {
            return options;
        }
        var sortType = Math.ceil(sortOrder / 2);
        var reverseSort = sortOrder % 2 === 0;
        if (sortType === 1) {
            options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.sortBy(options, 'text');
        }
        else if (sortType === 2) {
            options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.sortBy(options, function (opt) {
                var matches = opt.text.match(/.*?(\d+).*/);
                if (!matches || matches.length < 2) {
                    return -1;
                }
                else {
                    return parseInt(matches[1], 10);
                }
            });
        }
        else if (sortType === 3) {
            options = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.sortBy(options, function (opt) {
                return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.toLower(opt.text);
            });
        }
        if (reverseSort) {
            options = options.reverse();
        }
        return options;
    };
    QueryVariable.prototype.dependsOn = function (variable) {
        return Object(_variable__WEBPACK_IMPORTED_MODULE_1__["containsVariable"])(this.query, this.datasource, this.regex, variable.name);
    };
    return QueryVariable;
}());

// @ts-ignore
_variable__WEBPACK_IMPORTED_MODULE_1__["variableTypes"]['query'] = {
    name: 'Query',
    ctor: QueryVariable,
    description: 'Variable values are fetched from a datasource query',
    supportsMulti: true,
};


/***/ }),

/***/ "./public/app/features/templating/template_srv.ts":
/*!********************************************************!*\
  !*** ./public/app/features/templating/template_srv.ts ***!
  \********************************************************/
/*! exports provided: TemplateSrv, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TemplateSrv", function() { return TemplateSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_features_templating_variable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/templating/variable */ "./public/app/features/templating/variable.ts");




function luceneEscape(value) {
    return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1');
}
var TemplateSrv = /** @class */ (function () {
    function TemplateSrv() {
        this.regex = app_features_templating_variable__WEBPACK_IMPORTED_MODULE_3__["variableRegex"];
        this.index = {};
        this.grafanaVariables = {};
        this.builtIns = {};
        this.timeRange = null;
        this.fieldAccessorCache = {};
        this.builtIns['__interval'] = { text: '1s', value: '1s' };
        this.builtIns['__interval_ms'] = { text: '100', value: '100' };
        this.variables = [];
    }
    TemplateSrv.prototype.init = function (variables, timeRange) {
        this.variables = variables;
        this.timeRange = timeRange;
        this.updateIndex();
    };
    TemplateSrv.prototype.getBuiltInIntervalValue = function () {
        return this.builtIns.__interval.value;
    };
    TemplateSrv.prototype.updateIndex = function () {
        var _a;
        var existsOrEmpty = function (value) { return value || value === ''; };
        this.index = this.variables.reduce(function (acc, currentValue) {
            if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) {
                acc[currentValue.name] = currentValue;
            }
            return acc;
        }, {});
        if (this.timeRange) {
            var from = this.timeRange.from.valueOf().toString();
            var to = this.timeRange.to.valueOf().toString();
            this.index = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.index, (_a = {}, _a['__from'] = {
                current: { value: from, text: from },
            }, _a['__to'] = {
                current: { value: to, text: to },
            }, _a));
        }
    };
    TemplateSrv.prototype.updateTimeRange = function (timeRange) {
        this.timeRange = timeRange;
        this.updateIndex();
    };
    TemplateSrv.prototype.variableInitialized = function (variable) {
        this.index[variable.name] = variable;
    };
    TemplateSrv.prototype.getAdhocFilters = function (datasourceName) {
        var filters = [];
        if (this.variables) {
            for (var i = 0; i < this.variables.length; i++) {
                var variable = this.variables[i];
                if (variable.type !== 'adhoc') {
                    continue;
                }
                // null is the "default" datasource
                if (variable.datasource === null || variable.datasource === datasourceName) {
                    filters = filters.concat(variable.filters);
                }
                else if (variable.datasource.indexOf('$') === 0) {
                    if (this.replace(variable.datasource) === datasourceName) {
                        filters = filters.concat(variable.filters);
                    }
                }
            }
        }
        return filters;
    };
    TemplateSrv.prototype.luceneFormat = function (value) {
        if (typeof value === 'string') {
            return luceneEscape(value);
        }
        if (value instanceof Array && value.length === 0) {
            return '__empty__';
        }
        var quotedValues = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(value, function (val) {
            return '"' + luceneEscape(val) + '"';
        });
        return '(' + quotedValues.join(' OR ') + ')';
    };
    // encode string according to RFC 3986; in contrast to encodeURIComponent()
    // also the sub-delims "!", "'", "(", ")" and "*" are encoded;
    // unicode handling uses UTF-8 as in ECMA-262.
    TemplateSrv.prototype.encodeURIComponentStrict = function (str) {
        return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
            return ('%' +
                c
                    .charCodeAt(0)
                    .toString(16)
                    .toUpperCase());
        });
    };
    TemplateSrv.prototype.formatValue = function (value, format, variable) {
        // for some scopedVars there is no variable
        variable = variable || {};
        if (typeof format === 'function') {
            return format(value, variable, this.formatValue);
        }
        switch (format) {
            case 'regex': {
                if (typeof value === 'string') {
                    return app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__["default"].regexEscape(value);
                }
                var escapedValues = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(value, app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_1__["default"].regexEscape);
                if (escapedValues.length === 1) {
                    return escapedValues[0];
                }
                return '(' + escapedValues.join('|') + ')';
            }
            case 'lucene': {
                return this.luceneFormat(value);
            }
            case 'pipe': {
                if (typeof value === 'string') {
                    return value;
                }
                return value.join('|');
            }
            case 'distributed': {
                if (typeof value === 'string') {
                    return value;
                }
                return this.distributeVariable(value, variable.name);
            }
            case 'csv': {
                if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(value)) {
                    return value.join(',');
                }
                return value;
            }
            case 'json': {
                return JSON.stringify(value);
            }
            case 'percentencode': {
                // like glob, but url escaped
                if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(value)) {
                    return this.encodeURIComponentStrict('{' + value.join(',') + '}');
                }
                return this.encodeURIComponentStrict(value);
            }
            default: {
                if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(value) && value.length > 1) {
                    return '{' + value.join(',') + '}';
                }
                return value;
            }
        }
    };
    TemplateSrv.prototype.setGrafanaVariable = function (name, value) {
        this.grafanaVariables[name] = value;
    };
    TemplateSrv.prototype.getVariableName = function (expression) {
        this.regex.lastIndex = 0;
        var match = this.regex.exec(expression);
        if (!match) {
            return null;
        }
        var variableName = match.slice(1).find(function (match) { return match !== undefined; });
        return variableName;
    };
    TemplateSrv.prototype.variableExists = function (expression) {
        var name = this.getVariableName(expression);
        return name && this.index[name] !== void 0;
    };
    TemplateSrv.prototype.highlightVariablesAsHtml = function (str) {
        var _this = this;
        if (!str || !lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isString(str)) {
            return str;
        }
        str = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.escape(str);
        this.regex.lastIndex = 0;
        return str.replace(this.regex, function (match, var1, var2, fmt2, var3) {
            if (_this.index[var1 || var2 || var3] || _this.builtIns[var1 || var2 || var3]) {
                return '<span class="template-variable">' + match + '</span>';
            }
            return match;
        });
    };
    TemplateSrv.prototype.getAllValue = function (variable) {
        if (variable.allValue) {
            return variable.allValue;
        }
        var values = [];
        for (var i = 1; i < variable.options.length; i++) {
            values.push(variable.options[i].value);
        }
        return values;
    };
    TemplateSrv.prototype.getFieldAccessor = function (fieldPath) {
        var accessor = this.fieldAccessorCache[fieldPath];
        if (accessor) {
            return accessor;
        }
        return (this.fieldAccessorCache[fieldPath] = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.property(fieldPath));
    };
    TemplateSrv.prototype.getVariableValue = function (variableName, fieldPath, scopedVars) {
        var scopedVar = scopedVars[variableName];
        if (!scopedVar) {
            return null;
        }
        if (fieldPath) {
            return this.getFieldAccessor(fieldPath)(scopedVar.value);
        }
        return scopedVar.value;
    };
    TemplateSrv.prototype.replace = function (target, scopedVars, format) {
        var _this = this;
        if (!target) {
            return target;
        }
        this.regex.lastIndex = 0;
        return target.replace(this.regex, function (match, var1, var2, fmt2, var3, fieldPath, fmt3) {
            var variableName = var1 || var2 || var3;
            var variable = _this.index[variableName];
            var fmt = fmt2 || fmt3 || format;
            if (scopedVars) {
                var value_1 = _this.getVariableValue(variableName, fieldPath, scopedVars);
                if (value_1 !== null && value_1 !== undefined) {
                    return _this.formatValue(value_1, fmt, variable);
                }
            }
            if (!variable) {
                return match;
            }
            var systemValue = _this.grafanaVariables[variable.current.value];
            if (systemValue) {
                return _this.formatValue(systemValue, fmt, variable);
            }
            var value = variable.current.value;
            if (_this.isAllValue(value)) {
                value = _this.getAllValue(variable);
                // skip formatting of custom all values
                if (variable.allValue) {
                    return _this.replace(value);
                }
            }
            var res = _this.formatValue(value, fmt, variable);
            return res;
        });
    };
    TemplateSrv.prototype.isAllValue = function (value) {
        return value === '$__all' || (Array.isArray(value) && value[0] === '$__all');
    };
    TemplateSrv.prototype.replaceWithText = function (target, scopedVars) {
        var _this = this;
        if (!target) {
            return target;
        }
        var variable;
        this.regex.lastIndex = 0;
        return target.replace(this.regex, function (match, var1, var2, fmt2, var3) {
            if (scopedVars) {
                var option = scopedVars[var1 || var2 || var3];
                if (option) {
                    return option.text;
                }
            }
            variable = _this.index[var1 || var2 || var3];
            if (!variable) {
                return match;
            }
            var value = _this.grafanaVariables[variable.current.value];
            return typeof value === 'string' ? value : variable.current.text;
        });
    };
    TemplateSrv.prototype.fillVariableValuesForUrl = function (params, scopedVars) {
        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.each(this.variables, function (variable) {
            if (scopedVars && scopedVars[variable.name] !== void 0) {
                if (scopedVars[variable.name].skipUrlSync) {
                    return;
                }
                params['var-' + variable.name] = scopedVars[variable.name].value;
            }
            else {
                if (variable.skipUrlSync) {
                    return;
                }
                params['var-' + variable.name] = variable.getValueForUrl();
            }
        });
    };
    TemplateSrv.prototype.distributeVariable = function (value, variable) {
        value = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(value, function (val, index) {
            if (index !== 0) {
                return variable + '=' + val;
            }
            else {
                return val;
            }
        });
        return value.join(',');
    };
    return TemplateSrv;
}());

/* harmony default export */ __webpack_exports__["default"] = (new TemplateSrv());


/***/ }),

/***/ "./public/app/features/templating/variable.ts":
/*!****************************************************!*\
  !*** ./public/app/features/templating/variable.ts ***!
  \****************************************************/
/*! exports provided: variableRegex, variableRegexExec, variableTypes, assignModelProperties, containsVariable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variableRegex", function() { return variableRegex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variableRegexExec", function() { return variableRegexExec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variableTypes", function() { return variableTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "containsVariable", function() { return containsVariable; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_utils_model_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/model_utils */ "./public/app/core/utils/model_utils.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "assignModelProperties", function() { return app_core_utils_model_utils__WEBPACK_IMPORTED_MODULE_1__["assignModelProperties"]; });



/*
 * This regex matches 3 types of variable reference with an optional format specifier
 * \$(\w+)                          $var1
 * \[\[([\s\S]+?)(?::(\w+))?\]\]    [[var2]] or [[var2:fmt2]]
 * \${(\w+)(?::(\w+))?}             ${var3} or ${var3:fmt3}
 */
var variableRegex = /\$(\w+)|\[\[([\s\S]+?)(?::(\w+))?\]\]|\${(\w+)(?:\.([^:^\}]+))?(?::(\w+))?}/g;
// Helper function since lastIndex is not reset
var variableRegexExec = function (variableString) {
    variableRegex.lastIndex = 0;
    return variableRegex.exec(variableString);
};
var variableTypes = {};

function containsVariable() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var variableName = args[args.length - 1];
    args[0] = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(args[0]) ? args[0] : Object['values'](args[0]).join(' ');
    var variableString = args.slice(0, -1).join(' ');
    var matches = variableString.match(variableRegex);
    var isMatchingVariable = matches !== null
        ? matches.find(function (match) {
            var varMatch = variableRegexExec(match);
            return varMatch !== null && varMatch.indexOf(variableName) > -1;
        })
        : false;
    return !!isMatchingVariable;
}


/***/ }),

/***/ "./public/app/features/templating/variable_srv.ts":
/*!********************************************************!*\
  !*** ./public/app/features/templating/variable_srv.ts ***!
  \********************************************************/
/*! exports provided: VariableSrv */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VariableSrv", function() { return VariableSrv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./variable */ "./public/app/features/templating/variable.ts");
/* harmony import */ var app_core_utils_dag__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/utils/dag */ "./public/app/core/utils/dag.ts");

// Libaries


// Utils & Services



var VariableSrv = /** @class */ (function () {
    /** @ngInject */
    function VariableSrv($q, $location, $injector, templateSrv, timeSrv) {
        this.$q = $q;
        this.$location = $location;
        this.$injector = $injector;
        this.templateSrv = templateSrv;
        this.timeSrv = timeSrv;
    }
    VariableSrv.prototype.init = function (dashboard) {
        var e_1, _a;
        var _this = this;
        this.dashboard = dashboard;
        this.dashboard.events.on('time-range-updated', this.onTimeRangeUpdated.bind(this));
        this.dashboard.events.on('template-variable-value-updated', this.updateUrlParamsWithCurrentVariables.bind(this));
        // create working class models representing variables
        this.variables = dashboard.templating.list = dashboard.templating.list.map(this.createVariableFromModel.bind(this));
        this.templateSrv.init(this.variables, this.timeSrv.timeRange());
        try {
            // init variables
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.variables), _c = _b.next(); !_c.done; _c = _b.next()) {
                var variable = _c.value;
                variable.initLock = this.$q.defer();
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        var queryParams = this.$location.search();
        return this.$q
            .all(this.variables.map(function (variable) {
            return _this.processVariable(variable, queryParams);
        }))
            .then(function () {
            _this.templateSrv.updateIndex();
        });
    };
    VariableSrv.prototype.onTimeRangeUpdated = function (timeRange) {
        var _this = this;
        this.templateSrv.updateTimeRange(timeRange);
        var promises = this.variables
            .filter(function (variable) { return variable.refresh === 2; })
            .map(function (variable) {
            var previousOptions = variable.options.slice();
            return variable.updateOptions().then(function () {
                if (angular__WEBPACK_IMPORTED_MODULE_1___default.a.toJson(previousOptions) !== angular__WEBPACK_IMPORTED_MODULE_1___default.a.toJson(variable.options)) {
                    _this.dashboard.templateVariableValueUpdated();
                }
            });
        });
        return this.$q.all(promises).then(function () {
            _this.dashboard.startRefresh();
        });
    };
    VariableSrv.prototype.processVariable = function (variable, queryParams) {
        var e_2, _a;
        var _this = this;
        var dependencies = [];
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.variables), _c = _b.next(); !_c.done; _c = _b.next()) {
                var otherVariable = _c.value;
                if (variable.dependsOn(otherVariable)) {
                    dependencies.push(otherVariable.initLock.promise);
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return this.$q
            .all(dependencies)
            .then(function () {
            var urlValue = queryParams['var-' + variable.name];
            if (urlValue !== void 0) {
                return variable.setValueFromUrl(urlValue).then(variable.initLock.resolve);
            }
            if (variable.refresh === 1 || variable.refresh === 2) {
                return variable.updateOptions().then(variable.initLock.resolve);
            }
            variable.initLock.resolve();
        })
            .finally(function () {
            _this.templateSrv.variableInitialized(variable);
            delete variable.initLock;
        });
    };
    VariableSrv.prototype.createVariableFromModel = function (model) {
        // @ts-ignore
        var ctor = _variable__WEBPACK_IMPORTED_MODULE_4__["variableTypes"][model.type].ctor;
        if (!ctor) {
            throw {
                message: 'Unable to find variable constructor for ' + model.type,
            };
        }
        var variable = this.$injector.instantiate(ctor, { model: model });
        return variable;
    };
    VariableSrv.prototype.addVariable = function (variable) {
        this.variables.push(variable);
        this.templateSrv.updateIndex();
        this.dashboard.updateSubmenuVisibility();
    };
    VariableSrv.prototype.removeVariable = function (variable) {
        var index = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.indexOf(this.variables, variable);
        this.variables.splice(index, 1);
        this.templateSrv.updateIndex();
        this.dashboard.updateSubmenuVisibility();
    };
    VariableSrv.prototype.updateOptions = function (variable) {
        return variable.updateOptions();
    };
    VariableSrv.prototype.variableUpdated = function (variable, emitChangeEvents) {
        var _this = this;
        // if there is a variable lock ignore cascading update because we are in a boot up scenario
        if (variable.initLock) {
            return this.$q.when();
        }
        var g = this.createGraph();
        var node = g.getNode(variable.name);
        var promises = [];
        if (node) {
            promises = node.getOptimizedInputEdges().map(function (e) {
                return _this.updateOptions(_this.variables.find(function (v) { return v.name === e.inputNode.name; }));
            });
        }
        return this.$q.all(promises).then(function () {
            if (emitChangeEvents) {
                _this.dashboard.templateVariableValueUpdated();
                _this.dashboard.startRefresh();
            }
        });
    };
    VariableSrv.prototype.selectOptionsForCurrentValue = function (variable) {
        var i, y, value, option;
        var selected = [];
        for (i = 0; i < variable.options.length; i++) {
            option = variable.options[i];
            option.selected = false;
            if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(variable.current.value)) {
                for (y = 0; y < variable.current.value.length; y++) {
                    value = variable.current.value[y];
                    if (option.value === value) {
                        option.selected = true;
                        selected.push(option);
                    }
                }
            }
            else if (option.value === variable.current.value) {
                option.selected = true;
                selected.push(option);
            }
        }
        return selected;
    };
    VariableSrv.prototype.validateVariableSelectionState = function (variable) {
        if (!variable.current) {
            variable.current = {};
        }
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(variable.current.value)) {
            var selected = this.selectOptionsForCurrentValue(variable);
            // if none pick first
            if (selected.length === 0) {
                selected = variable.options[0];
            }
            else {
                selected = {
                    value: lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(selected, function (val) {
                        return val.value;
                    }),
                    text: lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(selected, function (val) {
                        return val.text;
                    }),
                };
            }
            return variable.setValue(selected);
        }
        else {
            var currentOption = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(variable.options, {
                text: variable.current.text,
            });
            if (currentOption) {
                return variable.setValue(currentOption);
            }
            else {
                if (!variable.options.length) {
                    return Promise.resolve();
                }
                return variable.setValue(variable.options[0]);
            }
        }
    };
    /**
     * Sets the current selected option (or options) based on the query params in the url. It is possible for values
     * in the url to not match current options of the variable. In that case the variables current value will be still set
     * to that value.
     * @param variable Instance of Variable
     * @param urlValue Value of the query parameter
     */
    VariableSrv.prototype.setOptionFromUrl = function (variable, urlValue) {
        var promise = this.$q.when();
        if (variable.refresh) {
            promise = variable.updateOptions();
        }
        return promise.then(function () {
            // Simple case. Value in url matches existing options text or value.
            var option = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(variable.options, function (op) {
                return op.text === urlValue || op.value === urlValue;
            });
            // No luck either it is array or value does not exist in the variables options.
            if (!option) {
                var defaultText = urlValue;
                var defaultValue = urlValue;
                if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(urlValue)) {
                    // Multiple values in the url. We construct text as a list of texts from all matched options.
                    defaultText = urlValue.reduce(function (acc, item) {
                        var t = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(variable.options, { value: item });
                        if (t) {
                            acc.push(t.text);
                        }
                        else {
                            acc.push(item);
                        }
                        return acc;
                    }, []);
                }
                // It is possible that we did not match the value to any existing option. In that case the url value will be
                // used anyway for both text and value.
                option = { text: defaultText, value: defaultValue };
            }
            if (variable.multi) {
                // In case variable is multiple choice, we cast to array to preserve the same behaviour as when selecting
                // the option directly, which will return even single value in an array.
                option = { text: lodash__WEBPACK_IMPORTED_MODULE_2___default.a.castArray(option.text), value: lodash__WEBPACK_IMPORTED_MODULE_2___default.a.castArray(option.value) };
            }
            return variable.setValue(option);
        });
    };
    VariableSrv.prototype.setOptionAsCurrent = function (variable, option) {
        variable.current = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.cloneDeep(option);
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(variable.current.text) && variable.current.text.length > 0) {
            variable.current.text = variable.current.text.join(' + ');
        }
        else if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(variable.current.value) && variable.current.value[0] !== '$__all') {
            variable.current.text = variable.current.value.join(' + ');
        }
        this.selectOptionsForCurrentValue(variable);
        return this.variableUpdated(variable);
    };
    VariableSrv.prototype.updateUrlParamsWithCurrentVariables = function () {
        // update url
        var params = this.$location.search();
        // remove variable params
        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.each(params, function (value, key) {
            if (key.indexOf('var-') === 0) {
                delete params[key];
            }
        });
        // add new values
        this.templateSrv.fillVariableValuesForUrl(params);
        // update url
        this.$location.search(params);
    };
    VariableSrv.prototype.setAdhocFilter = function (options) {
        var variable = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(this.variables, {
            type: 'adhoc',
            datasource: options.datasource,
        });
        if (!variable) {
            variable = this.createVariableFromModel({
                name: 'Filters',
                type: 'adhoc',
                datasource: options.datasource,
            });
            this.addVariable(variable);
        }
        var filters = variable.filters;
        var filter = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(filters, { key: options.key, value: options.value });
        if (!filter) {
            filter = { key: options.key, value: options.value };
            filters.push(filter);
        }
        filter.operator = options.operator;
        this.variableUpdated(variable, true);
    };
    VariableSrv.prototype.createGraph = function () {
        var _this = this;
        var g = new app_core_utils_dag__WEBPACK_IMPORTED_MODULE_5__["Graph"]();
        this.variables.forEach(function (v) {
            g.createNode(v.name);
        });
        this.variables.forEach(function (v1) {
            _this.variables.forEach(function (v2) {
                if (v1 === v2) {
                    return;
                }
                if (v1.dependsOn(v2)) {
                    g.link(v1.name, v2.name);
                }
            });
        });
        return g;
    };
    return VariableSrv;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_3__["default"].service('variableSrv', VariableSrv);


/***/ }),

/***/ "./public/app/features/users/state/actions.ts":
/*!****************************************************!*\
  !*** ./public/app/features/users/state/actions.ts ***!
  \****************************************************/
/*! exports provided: ActionTypes, setUsersSearchQuery, loadUsers, loadInvitees, updateUser, removeUser, revokeInvite */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUsersSearchQuery", function() { return setUsersSearchQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadUsers", function() { return loadUsers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadInvitees", function() { return loadInvitees; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateUser", function() { return updateUser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeUser", function() { return removeUser; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "revokeInvite", function() { return revokeInvite; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");


var ActionTypes;
(function (ActionTypes) {
    ActionTypes["LoadUsers"] = "LOAD_USERS";
    ActionTypes["LoadInvitees"] = "LOAD_INVITEES";
    ActionTypes["SetUsersSearchQuery"] = "SET_USERS_SEARCH_QUERY";
})(ActionTypes || (ActionTypes = {}));
var usersLoaded = function (users) { return ({
    type: ActionTypes.LoadUsers,
    payload: users,
}); };
var inviteesLoaded = function (invitees) { return ({
    type: ActionTypes.LoadInvitees,
    payload: invitees,
}); };
var setUsersSearchQuery = function (query) { return ({
    type: ActionTypes.SetUsersSearchQuery,
    payload: query,
}); };
function loadUsers() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var users;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/org/users')];
                case 1:
                    users = _a.sent();
                    dispatch(usersLoaded(users));
                    return [2 /*return*/];
            }
        });
    }); };
}
function loadInvitees() {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        var invitees;
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().get('/api/org/invites')];
                case 1:
                    invitees = _a.sent();
                    dispatch(inviteesLoaded(invitees));
                    return [2 /*return*/];
            }
        });
    }); };
}
function updateUser(user) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().patch("/api/org/users/" + user.userId, { role: user.role })];
                case 1:
                    _a.sent();
                    dispatch(loadUsers());
                    return [2 /*return*/];
            }
        });
    }); };
}
function removeUser(userId) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().delete("/api/org/users/" + userId)];
                case 1:
                    _a.sent();
                    dispatch(loadUsers());
                    return [2 /*return*/];
            }
        });
    }); };
}
function revokeInvite(code) {
    var _this = this;
    return function (dispatch) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_1__["getBackendSrv"])().patch("/api/org/invites/" + code + "/revoke", {})];
                case 1:
                    _a.sent();
                    dispatch(loadInvitees());
                    return [2 /*return*/];
            }
        });
    }); };
}


/***/ }),

/***/ "./public/app/features/users/state/reducers.ts":
/*!*****************************************************!*\
  !*** ./public/app/features/users/state/reducers.ts ***!
  \*****************************************************/
/*! exports provided: initialState, usersReducer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initialState", function() { return initialState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "usersReducer", function() { return usersReducer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actions */ "./public/app/features/users/state/actions.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");



var initialState = {
    invitees: [],
    users: [],
    searchQuery: '',
    canInvite: !app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].externalUserMngLinkName,
    externalUserMngInfo: app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].externalUserMngInfo,
    externalUserMngLinkName: app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].externalUserMngLinkName,
    externalUserMngLinkUrl: app_core_config__WEBPACK_IMPORTED_MODULE_2__["default"].externalUserMngLinkUrl,
    hasFetched: false,
};
var usersReducer = function (state, action) {
    if (state === void 0) { state = initialState; }
    switch (action.type) {
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadUsers:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hasFetched: true, users: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].LoadInvitees:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { hasFetched: true, invitees: action.payload });
        case _actions__WEBPACK_IMPORTED_MODULE_1__["ActionTypes"].SetUsersSearchQuery:
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { searchQuery: action.payload });
    }
    return state;
};
/* harmony default export */ __webpack_exports__["default"] = ({
    users: usersReducer,
});


/***/ }),

/***/ "./public/app/index.ts":
/*!*****************************!*\
  !*** ./public/app/index.ts ***!
  \*****************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./app */ "./public/app/app.ts");

_app__WEBPACK_IMPORTED_MODULE_0__["default"].init();


/***/ }),

/***/ "./public/app/plugins/datasource/dashboard/DashboardQueryEditor.tsx":
/*!**************************************************************************!*\
  !*** ./public/app/plugins/datasource/dashboard/DashboardQueryEditor.tsx ***!
  \**************************************************************************/
/*! exports provided: DashboardQueryEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardQueryEditor", function() { return DashboardQueryEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");
/* harmony import */ var app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/plugins/datasource_srv */ "./public/app/features/plugins/datasource_srv.ts");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./types */ "./public/app/plugins/datasource/dashboard/types.ts");
/* harmony import */ var app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/features/dashboard/services/DashboardSrv */ "./public/app/features/dashboard/services/DashboardSrv.ts");
/* harmony import */ var app_features_dashboard_panel_editor_QueryEditorRow__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/features/dashboard/panel_editor/QueryEditorRow */ "./public/app/features/dashboard/panel_editor/QueryEditorRow.tsx");

// Libraries

// Types







function getQueryDisplayText(query) {
    return JSON.stringify(query);
}
var DashboardQueryEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DashboardQueryEditor, _super);
    function DashboardQueryEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.onPanelChanged = function (id) {
            var onChange = _this.props.onChange;
            var query = _this.getQuery();
            query.panelId = id;
            onChange(query);
            // Update the
            _this.props.panel.refresh();
        };
        _this.getPanelDescription = function (panel) {
            var defaultDatasource = _this.state.defaultDatasource;
            var dsname = panel.datasource ? panel.datasource : defaultDatasource;
            if (panel.targets.length === 1) {
                return '1 query to ' + dsname;
            }
            return panel.targets.length + ' queries to ' + dsname;
        };
        _this.state = {
            defaultDatasource: '',
            results: [],
        };
        return _this;
    }
    DashboardQueryEditor.prototype.getQuery = function () {
        var panel = this.props.panel;
        return panel.targets[0];
    };
    DashboardQueryEditor.prototype.componentDidMount = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                this.componentDidUpdate(null);
                return [2 /*return*/];
            });
        });
    };
    DashboardQueryEditor.prototype.componentDidUpdate = function (prevProps) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var panelData, query, defaultDS, dashboard, panel, mainDS, info, _a, _b, query_1, ds, _c, fmt, qData, queryData, e_1_1;
            var e_1, _d;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_e) {
                switch (_e.label) {
                    case 0:
                        panelData = this.props.panelData;
                        if (!(!prevProps || prevProps.panelData !== panelData)) return [3 /*break*/, 13];
                        query = this.props.panel.targets[0];
                        return [4 /*yield*/, Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_5__["getDatasourceSrv"])().get(null)];
                    case 1:
                        defaultDS = _e.sent();
                        dashboard = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__["getDashboardSrv"])().getCurrent();
                        panel = dashboard.getPanelById(query.panelId);
                        if (!panel) {
                            this.setState({ defaultDatasource: defaultDS.name });
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_5__["getDatasourceSrv"])().get(panel.datasource)];
                    case 2:
                        mainDS = _e.sent();
                        info = [];
                        _e.label = 3;
                    case 3:
                        _e.trys.push([3, 10, 11, 12]);
                        _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.targets), _b = _a.next();
                        _e.label = 4;
                    case 4:
                        if (!!_b.done) return [3 /*break*/, 9];
                        query_1 = _b.value;
                        if (!query_1.datasource) return [3 /*break*/, 6];
                        return [4 /*yield*/, Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_5__["getDatasourceSrv"])().get(query_1.datasource)];
                    case 5:
                        _c = _e.sent();
                        return [3 /*break*/, 7];
                    case 6:
                        _c = mainDS;
                        _e.label = 7;
                    case 7:
                        ds = _c;
                        fmt = ds.getQueryDisplayText ? ds.getQueryDisplayText : getQueryDisplayText;
                        qData = Object(app_features_dashboard_panel_editor_QueryEditorRow__WEBPACK_IMPORTED_MODULE_8__["filterPanelDataToQuery"])(panelData, query_1.refId);
                        queryData = qData ? qData : panelData;
                        info.push({
                            refId: query_1.refId,
                            query: fmt(query_1),
                            img: ds.meta.info.logos.small,
                            data: queryData.series,
                            error: queryData.error,
                        });
                        _e.label = 8;
                    case 8:
                        _b = _a.next();
                        return [3 /*break*/, 4];
                    case 9: return [3 /*break*/, 12];
                    case 10:
                        e_1_1 = _e.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 12];
                    case 11:
                        try {
                            if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7 /*endfinally*/];
                    case 12:
                        this.setState({ defaultDatasource: defaultDS.name, results: info });
                        _e.label = 13;
                    case 13: return [2 /*return*/];
                }
            });
        });
    };
    DashboardQueryEditor.prototype.renderQueryData = function (editURL) {
        var results = this.state.results;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, results.map(function (target, index) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__header", key: index },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__ref-id" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { src: target.img, width: 16, className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])({ marginRight: '8px' }) }),
                    target.refId,
                    ":"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "query-editor-row__collapsed-text" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { href: editURL },
                        target.query,
                        "\u00A0",
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-external-link" })))));
        })));
    };
    DashboardQueryEditor.prototype.render = function () {
        var e_2, _a;
        var _this = this;
        var dashboard = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__["getDashboardSrv"])().getCurrent();
        var query = this.getQuery();
        var selected;
        var panels = [];
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dashboard.panels), _c = _b.next(); !_c.done; _c = _b.next()) {
                var panel = _c.value;
                var plugin = app_core_config__WEBPACK_IMPORTED_MODULE_3__["default"].panels[panel.type];
                if (!plugin) {
                    continue;
                }
                if (panel.targets && panel.datasource !== _types__WEBPACK_IMPORTED_MODULE_6__["SHARED_DASHBODARD_QUERY"]) {
                    var item = {
                        value: panel.id,
                        label: panel.title ? panel.title : 'Panel ' + panel.id,
                        description: this.getPanelDescription(panel),
                        imgUrl: plugin.info.logos.small,
                    };
                    panels.push(item);
                    if (query.panelId === panel.id) {
                        selected = item;
                    }
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
        if (panels.length < 1) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])({ padding: '10px' }) }, "This dashboard does not have other panels. Add queries to other panels and try again"));
        }
        // Same as current URL, but different panelId
        var editURL = "d/" + dashboard.uid + "/" + dashboard.title + "?&fullscreen&edit&panelId=" + query.panelId;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label" }, "Use results from panel"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { placeholder: "Choose Panel", isSearchable: true, options: panels, value: selected, onChange: function (item) { return _this.onPanelChanged(item.value); } })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_4__["css"])({ padding: '16px' }) }, query.panelId && this.renderQueryData(editURL))));
    };
    return DashboardQueryEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/datasource/dashboard/index.ts":
/*!**********************************************************!*\
  !*** ./public/app/plugins/datasource/dashboard/index.ts ***!
  \**********************************************************/
/*! exports provided: isSharedDashboardQuery, runSharedRequest, DashboardQueryEditor, SHARED_DASHBODARD_QUERY */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _runSharedRequest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./runSharedRequest */ "./public/app/plugins/datasource/dashboard/runSharedRequest.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isSharedDashboardQuery", function() { return _runSharedRequest__WEBPACK_IMPORTED_MODULE_0__["isSharedDashboardQuery"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "runSharedRequest", function() { return _runSharedRequest__WEBPACK_IMPORTED_MODULE_0__["runSharedRequest"]; });

/* harmony import */ var _DashboardQueryEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DashboardQueryEditor */ "./public/app/plugins/datasource/dashboard/DashboardQueryEditor.tsx");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashboardQueryEditor", function() { return _DashboardQueryEditor__WEBPACK_IMPORTED_MODULE_1__["DashboardQueryEditor"]; });

/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./types */ "./public/app/plugins/datasource/dashboard/types.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SHARED_DASHBODARD_QUERY", function() { return _types__WEBPACK_IMPORTED_MODULE_2__["SHARED_DASHBODARD_QUERY"]; });






/***/ }),

/***/ "./public/app/plugins/datasource/dashboard/runSharedRequest.ts":
/*!*********************************************************************!*\
  !*** ./public/app/plugins/datasource/dashboard/runSharedRequest.ts ***!
  \*********************************************************************/
/*! exports provided: isSharedDashboardQuery, runSharedRequest */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSharedDashboardQuery", function() { return isSharedDashboardQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runSharedRequest", function() { return runSharedRequest; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/_esm5/index.js");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./types */ "./public/app/plugins/datasource/dashboard/types.ts");
/* harmony import */ var app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/dashboard/services/DashboardSrv */ "./public/app/features/dashboard/services/DashboardSrv.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");





function isSharedDashboardQuery(datasource) {
    if (!datasource) {
        // default datasource
        return false;
    }
    if (datasource === _types__WEBPACK_IMPORTED_MODULE_2__["SHARED_DASHBODARD_QUERY"]) {
        return true;
    }
    var ds = datasource;
    return ds.meta && ds.meta.name === _types__WEBPACK_IMPORTED_MODULE_2__["SHARED_DASHBODARD_QUERY"];
}
function runSharedRequest(options) {
    return new rxjs__WEBPACK_IMPORTED_MODULE_1__["Observable"](function (subscriber) {
        var dashboard = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_3__["getDashboardSrv"])().getCurrent();
        var listenToPanelId = getPanelIdFromQuery(options.queries);
        if (!listenToPanelId) {
            subscriber.next(getQueryError('Missing panel reference ID'));
            return null;
        }
        var currentPanel = dashboard.getPanelById(options.panelId);
        var listenToPanel = dashboard.getPanelById(listenToPanelId);
        if (!listenToPanel) {
            subscriber.next(getQueryError('Unknown Panel: ' + listenToPanelId));
            return null;
        }
        var listenToRunner = listenToPanel.getQueryRunner();
        var subscription = listenToRunner.getData(false).subscribe({
            next: function (data) {
                console.log('got data from other panel', data);
                subscriber.next(data);
            },
        });
        // If we are in fullscreen the other panel will not execute any queries
        // So we have to trigger it from here
        if (currentPanel.fullscreen) {
            var datasource = listenToPanel.datasource, targets = listenToPanel.targets;
            var modified = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { datasource: datasource, panelId: listenToPanelId, queries: targets });
            listenToRunner.run(modified);
        }
        return function () {
            console.log('runSharedRequest unsubscribe');
            subscription.unsubscribe();
        };
    });
}
function getPanelIdFromQuery(queries) {
    if (!queries || !queries.length) {
        return undefined;
    }
    return queries[0].panelId;
}
function getQueryError(msg) {
    return {
        state: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["LoadingState"].Error,
        series: [],
        error: { message: msg },
        timeRange: _grafana_data__WEBPACK_IMPORTED_MODULE_4__["DefaultTimeRange"],
    };
}


/***/ }),

/***/ "./public/app/plugins/datasource/dashboard/types.ts":
/*!**********************************************************!*\
  !*** ./public/app/plugins/datasource/dashboard/types.ts ***!
  \**********************************************************/
/*! exports provided: SHARED_DASHBODARD_QUERY */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SHARED_DASHBODARD_QUERY", function() { return SHARED_DASHBODARD_QUERY; });
var SHARED_DASHBODARD_QUERY = '-- Dashboard --';


/***/ }),

/***/ "./public/app/plugins/datasource/graphite/FunctionEditor.tsx":
/*!*******************************************************************!*\
  !*** ./public/app/plugins/datasource/graphite/FunctionEditor.tsx ***!
  \*******************************************************************/
/*! exports provided: FunctionEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FunctionEditor", function() { return FunctionEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _FunctionEditorControls__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./FunctionEditorControls */ "./public/app/plugins/datasource/graphite/FunctionEditorControls.tsx");
var _this = undefined;




var FunctionDescription = react__WEBPACK_IMPORTED_MODULE_1___default.a.lazy(function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    var rst2html;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, __webpack_require__.e(/*! import() | rst2html */ "rst2html").then(__webpack_require__.t.bind(null, /*! rst2html */ "./node_modules/rst2html/dist/rst2html.min.js", 7))];
            case 1:
                rst2html = (_a.sent()).default;
                return [2 /*return*/, {
                        default: function (props) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { dangerouslySetInnerHTML: { __html: rst2html(props.description) } })); },
                    }];
        }
    });
}); });
var FunctionEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FunctionEditor, _super);
    function FunctionEditor(props) {
        var _this = _super.call(this, props) || this;
        _this.triggerRef = react__WEBPACK_IMPORTED_MODULE_1___default.a.createRef();
        _this.renderContent = function (_a) {
            var updatePopperPosition = _a.updatePopperPosition;
            var _b = _this.props, onMoveLeft = _b.onMoveLeft, onMoveRight = _b.onMoveRight, _c = _b.func.def, name = _c.name, description = _c.description;
            var showingDescription = _this.state.showingDescription;
            if (showingDescription) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: { overflow: 'auto', maxHeight: '30rem', textAlign: 'left', fontWeight: 'normal' } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h4", { style: { color: 'white' } },
                        " ",
                        name,
                        " "),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1__["Suspense"], { fallback: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, "Loading description...") },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(FunctionDescription, { description: description }))));
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FunctionEditorControls__WEBPACK_IMPORTED_MODULE_3__["FunctionEditorControls"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props, { onMoveLeft: function () {
                    onMoveLeft(_this.props.func);
                    updatePopperPosition();
                }, onMoveRight: function () {
                    onMoveRight(_this.props.func);
                    updatePopperPosition();
                }, onDescriptionShow: function () {
                    _this.setState({ showingDescription: true }, function () {
                        updatePopperPosition();
                    });
                } })));
        };
        _this.state = {
            showingDescription: false,
        };
        return _this;
    }
    FunctionEditor.prototype.render = function () {
        var _this = this;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PopoverController"], { content: this.renderContent, placement: "top", hideAfter: 300 }, function (showPopper, hidePopper, popperProps) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                _this.triggerRef && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Popover"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, popperProps, { referenceElement: _this.triggerRef.current, wrapperClassName: "popper", className: "popper__background", onMouseLeave: function () {
                        _this.setState({ showingDescription: false });
                        hidePopper();
                    }, onMouseEnter: showPopper, renderArrow: function (_a) {
                        var arrowProps = _a.arrowProps, placement = _a.placement;
                        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ className: "popper__arrow", "data-placement": placement }, arrowProps)));
                    } }))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { ref: _this.triggerRef, onClick: popperProps.show ? hidePopper : showPopper, onMouseLeave: function () {
                        hidePopper();
                        _this.setState({ showingDescription: false });
                    }, style: { cursor: 'pointer' } }, _this.props.func.def.name)));
        }));
    };
    return FunctionEditor;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));



/***/ }),

/***/ "./public/app/plugins/datasource/graphite/FunctionEditorControls.tsx":
/*!***************************************************************************!*\
  !*** ./public/app/plugins/datasource/graphite/FunctionEditorControls.tsx ***!
  \***************************************************************************/
/*! exports provided: FunctionEditorControls */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FunctionEditorControls", function() { return FunctionEditorControls; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var FunctionHelpButton = function (props) {
    if (props.description) {
        return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "pointer fa fa-question-circle", onClick: props.onDescriptionShow });
    }
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "pointer fa fa-question-circle", onClick: function () {
            window.open('http://graphite.readthedocs.org/en/latest/functions.html#graphite.render.functions.' + props.name, '_blank');
        } }));
};
var FunctionEditorControls = function (props) {
    var func = props.func, onMoveLeft = props.onMoveLeft, onMoveRight = props.onMoveRight, onRemove = props.onRemove, onDescriptionShow = props.onDescriptionShow;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { style: {
            display: 'flex',
            width: '60px',
            justifyContent: 'space-between',
        } },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "pointer fa fa-arrow-left", onClick: function () { return onMoveLeft(func); } }),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(FunctionHelpButton, { name: func.def.name, description: func.def.description, onDescriptionShow: onDescriptionShow }),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "pointer fa fa-remove", onClick: function () { return onRemove(func); } }),
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", { className: "pointer fa fa-arrow-right", onClick: function () { return onMoveRight(func); } })));
};


/***/ }),

/***/ "./public/app/plugins/datasource/loki/components/AnnotationsQueryEditor.tsx":
/*!**********************************************************************************!*\
  !*** ./public/app/plugins/datasource/loki/components/AnnotationsQueryEditor.tsx ***!
  \**********************************************************************************/
/*! exports provided: LokiAnnotationsQueryEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LokiAnnotationsQueryEditor", function() { return LokiAnnotationsQueryEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _useLokiSyntax__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./useLokiSyntax */ "./public/app/plugins/datasource/loki/components/useLokiSyntax.ts");
/* harmony import */ var _LokiQueryFieldForm__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LokiQueryFieldForm */ "./public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx");

// Libraries

// Types



var LokiAnnotationsQueryEditor = Object(react__WEBPACK_IMPORTED_MODULE_1__["memo"])(function LokiAnnotationQueryEditor(props) {
    var expr = props.expr, datasource = props.datasource, onChange = props.onChange;
    // Timerange to get existing labels from. Hard coding like this seems to be good enough right now.
    var absolute = {
        from: Date.now() - 10000,
        to: Date.now(),
    };
    var _a = Object(_useLokiSyntax__WEBPACK_IMPORTED_MODULE_3__["useLokiSyntax"])(datasource.languageProvider, _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DataSourceStatus"].Connected, absolute), isSyntaxReady = _a.isSyntaxReady, setActiveOption = _a.setActiveOption, refreshLabels = _a.refreshLabels, syntaxProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["isSyntaxReady", "setActiveOption", "refreshLabels"]);
    var query = {
        refId: '',
        expr: expr,
    };
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-group" },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_LokiQueryFieldForm__WEBPACK_IMPORTED_MODULE_4__["LokiQueryFieldForm"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ datasource: datasource, datasourceStatus: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DataSourceStatus"].Connected, query: query, onChange: function (query) { return onChange(query.expr); }, onRunQuery: function () { }, history: [], panelData: null, onLoadOptions: setActiveOption, onLabelsRefresh: refreshLabels, syntaxLoaded: isSyntaxReady, absoluteRange: absolute }, syntaxProps))));
});


/***/ }),

/***/ "./public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx":
/*!******************************************************************************!*\
  !*** ./public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx ***!
  \******************************************************************************/
/*! exports provided: LokiQueryFieldForm */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LokiQueryFieldForm", function() { return LokiQueryFieldForm; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var rc_cascader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rc-cascader */ "./node_modules/rc-cascader/es/index.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_explore_QueryField__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/explore/QueryField */ "./public/app/features/explore/QueryField.tsx");
/* harmony import */ var app_features_explore_slate_plugins_braces__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/explore/slate-plugins/braces */ "./public/app/features/explore/slate-plugins/braces.ts");

// Libraries

// @ts-ignore


// Components

// Utils & Services
// dom also includes Element polyfills


function getChooserText(hasSyntax, hasLogLabels, datasourceStatus) {
    if (datasourceStatus === _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DataSourceStatus"].Disconnected) {
        return '(Disconnected)';
    }
    if (!hasSyntax) {
        return 'Loading labels...';
    }
    if (!hasLogLabels) {
        return '(No labels found)';
    }
    return 'Log labels';
}
function willApplySuggestion(suggestion, _a) {
    var typeaheadContext = _a.typeaheadContext, typeaheadText = _a.typeaheadText;
    // Modify suggestion based on context
    switch (typeaheadContext) {
        case 'context-labels': {
            var nextChar = _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DOMUtil"].getNextCharacter();
            if (!nextChar || nextChar === '}' || nextChar === ',') {
                suggestion += '=';
            }
            break;
        }
        case 'context-label-values': {
            // Always add quotes and remove existing ones instead
            if (!typeaheadText.match(/^(!?=~?"|")/)) {
                suggestion = "\"" + suggestion;
            }
            if (_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DOMUtil"].getNextCharacter() !== '"') {
                suggestion = suggestion + "\"";
            }
            break;
        }
        default:
    }
    return suggestion;
}
var LokiQueryFieldForm = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LokiQueryFieldForm, _super);
    function LokiQueryFieldForm(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.loadOptions = function (selectedOptions) {
            _this.props.onLoadOptions(selectedOptions);
        };
        _this.onChangeLogLabels = function (values, selectedOptions) {
            if (selectedOptions.length === 2) {
                var key = selectedOptions[0].value;
                var value = selectedOptions[1].value;
                var query = "{" + key + "=\"" + value + "\"}";
                _this.onChangeQuery(query, true);
            }
        };
        _this.onChangeQuery = function (value, override) {
            // Send text change to parent
            var _a = _this.props, query = _a.query, onChange = _a.onChange, onRunQuery = _a.onRunQuery;
            if (onChange) {
                var nextQuery = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, query, { expr: value });
                onChange(nextQuery);
                if (override && onRunQuery) {
                    onRunQuery();
                }
            }
        };
        _this.onTypeahead = function (typeahead) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, Promise, function () {
            var datasource, lokiLanguageProvider, _a, history, absoluteRange, prefix, text, value, wrapperClasses, labelKey, result;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
                switch (_b.label) {
                    case 0:
                        datasource = this.props.datasource;
                        if (!datasource.languageProvider) {
                            return [2 /*return*/, { suggestions: [] }];
                        }
                        lokiLanguageProvider = datasource.languageProvider;
                        _a = this.props, history = _a.history, absoluteRange = _a.absoluteRange;
                        prefix = typeahead.prefix, text = typeahead.text, value = typeahead.value, wrapperClasses = typeahead.wrapperClasses, labelKey = typeahead.labelKey;
                        return [4 /*yield*/, lokiLanguageProvider.provideCompletionItems({ text: text, value: value, prefix: prefix, wrapperClasses: wrapperClasses, labelKey: labelKey }, { history: history, absoluteRange: absoluteRange })];
                    case 1:
                        result = _b.sent();
                        //console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
                        return [2 /*return*/, result];
                }
            });
        }); };
        _this.plugins = [
            Object(app_features_explore_slate_plugins_braces__WEBPACK_IMPORTED_MODULE_5__["default"])(),
            Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["SlatePrism"])({
                onlyIn: function (node) { return node.object === 'block' && node.type === 'code_block'; },
                getSyntax: function (node) { return 'promql'; },
            }),
        ];
        return _this;
    }
    LokiQueryFieldForm.prototype.render = function () {
        var _a = this.props, queryResponse = _a.queryResponse, query = _a.query, syntaxLoaded = _a.syntaxLoaded, logLabelOptions = _a.logLabelOptions, onLoadOptions = _a.onLoadOptions, onLabelsRefresh = _a.onLabelsRefresh, datasource = _a.datasource, datasourceStatus = _a.datasourceStatus;
        var lokiLanguageProvider = datasource.languageProvider;
        var cleanText = datasource.languageProvider ? lokiLanguageProvider.cleanText : undefined;
        var hasLogLabels = logLabelOptions && logLabelOptions.length > 0;
        var chooserText = getChooserText(syntaxLoaded, hasLogLabels, datasourceStatus);
        var buttonDisabled = !syntaxLoaded || datasourceStatus === _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DataSourceStatus"].Disconnected;
        var showError = queryResponse && queryResponse.error && queryResponse.error.refId === query.refId;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(rc_cascader__WEBPACK_IMPORTED_MODULE_2__["default"], { options: logLabelOptions, onChange: this.onChangeLogLabels, loadData: onLoadOptions, expandIcon: null, onPopupVisibleChange: function (isVisible) {
                            if (isVisible && onLabelsRefresh) {
                                onLabelsRefresh();
                            }
                        } },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "gf-form-label gf-form-label--btn", disabled: buttonDisabled },
                            chooserText,
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-down" })))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_features_explore_QueryField__WEBPACK_IMPORTED_MODULE_4__["default"], { additionalPlugins: this.plugins, cleanText: cleanText, query: query.expr, onTypeahead: this.onTypeahead, onWillApplySuggestion: willApplySuggestion, onChange: this.onChangeQuery, onRunQuery: this.props.onRunQuery, placeholder: "Enter a Loki query", portalOrigin: "loki", syntaxLoaded: syntaxLoaded }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, showError ? react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "prom-query-field-info text-error" }, queryResponse.error.message) : null)));
    };
    return LokiQueryFieldForm;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent));



/***/ }),

/***/ "./public/app/plugins/datasource/loki/components/useLokiLabels.ts":
/*!************************************************************************!*\
  !*** ./public/app/plugins/datasource/loki/components/useLokiLabels.ts ***!
  \************************************************************************/
/*! exports provided: useLokiLabels */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "useLokiLabels", function() { return useLokiLabels; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui_src_types_datasource__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui/src/types/datasource */ "./packages/grafana-ui/src/types/datasource.ts");
/* harmony import */ var app_core_hooks_useRefMounted__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/hooks/useRefMounted */ "./public/app/core/hooks/useRefMounted.ts");
var _this = undefined;




/**
 *
 * @param languageProvider
 * @param languageProviderInitialised
 * @param activeOption rc-cascader provided option used to fetch option's values that hasn't been loaded yet
 *
 * @description Fetches missing labels and enables labels refresh
 */
var useLokiLabels = function (languageProvider, languageProviderInitialised, activeOption, absoluteRange, datasourceStatus, initialDatasourceStatus // used for test purposes
) {
    var mounted = Object(app_core_hooks_useRefMounted__WEBPACK_IMPORTED_MODULE_3__["useRefMounted"])();
    // State
    var _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])([]), 2), logLabelOptions = _a[0], setLogLabelOptions = _a[1];
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(false), 2), shouldTryRefreshLabels = _b[0], setRefreshLabels = _b[1];
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(initialDatasourceStatus || _grafana_ui_src_types_datasource__WEBPACK_IMPORTED_MODULE_2__["DataSourceStatus"].Connected), 2), prevDatasourceStatus = _c[0], setPrevDatasourceStatus = _c[1];
    var _d = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(false), 2), shouldForceRefreshLabels = _d[0], setForceRefreshLabels = _d[1];
    // Async
    var fetchOptionValues = function (option) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, languageProvider.fetchLabelValues(option, absoluteRange)];
                case 1:
                    _a.sent();
                    if (mounted.current) {
                        setLogLabelOptions(languageProvider.logLabelOptions);
                    }
                    return [2 /*return*/];
            }
        });
    }); };
    var tryLabelsRefresh = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, languageProvider.refreshLogLabels(absoluteRange, shouldForceRefreshLabels)];
                case 1:
                    _a.sent();
                    if (mounted.current) {
                        setRefreshLabels(false);
                        setForceRefreshLabels(false);
                        setLogLabelOptions(languageProvider.logLabelOptions);
                    }
                    return [2 /*return*/];
            }
        });
    }); };
    // Effects
    // This effect performs loading of options that hasn't been loaded yet
    // It's a subject of activeOption state change only. This is because of specific behavior or rc-cascader
    // https://github.com/react-component/cascader/blob/master/src/Cascader.jsx#L165
    Object(react__WEBPACK_IMPORTED_MODULE_1__["useEffect"])(function () {
        if (languageProviderInitialised) {
            var targetOption_1 = activeOption[activeOption.length - 1];
            if (targetOption_1) {
                var nextOptions = logLabelOptions.map(function (option) {
                    if (option.value === targetOption_1.value) {
                        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, option, { loading: true });
                    }
                    return option;
                });
                setLogLabelOptions(nextOptions); // to set loading
                fetchOptionValues(targetOption_1.value);
            }
        }
    }, [activeOption]);
    // This effect is performed on shouldTryRefreshLabels or shouldForceRefreshLabels state change only.
    // Since shouldTryRefreshLabels is reset AFTER the labels are refreshed we are secured in case of trying to refresh
    // when previous refresh hasn't finished yet
    Object(react__WEBPACK_IMPORTED_MODULE_1__["useEffect"])(function () {
        if (shouldTryRefreshLabels || shouldForceRefreshLabels) {
            tryLabelsRefresh();
        }
    }, [shouldTryRefreshLabels, shouldForceRefreshLabels]);
    // This effect is performed on datasourceStatus state change only.
    // We want to make sure to only force refresh AFTER a disconnected state thats why we store the previous datasourceStatus in state
    Object(react__WEBPACK_IMPORTED_MODULE_1__["useEffect"])(function () {
        if (datasourceStatus === _grafana_ui_src_types_datasource__WEBPACK_IMPORTED_MODULE_2__["DataSourceStatus"].Connected && prevDatasourceStatus === _grafana_ui_src_types_datasource__WEBPACK_IMPORTED_MODULE_2__["DataSourceStatus"].Disconnected) {
            setForceRefreshLabels(true);
        }
        setPrevDatasourceStatus(datasourceStatus);
    }, [datasourceStatus]);
    return {
        logLabelOptions: logLabelOptions,
        setLogLabelOptions: setLogLabelOptions,
        refreshLabels: function () { return setRefreshLabels(true); },
    };
};


/***/ }),

/***/ "./public/app/plugins/datasource/loki/components/useLokiSyntax.ts":
/*!************************************************************************!*\
  !*** ./public/app/plugins/datasource/loki/components/useLokiSyntax.ts ***!
  \************************************************************************/
/*! exports provided: useLokiSyntax */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "useLokiSyntax", function() { return useLokiSyntax; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prismjs */ "./node_modules/prismjs/prism.js");
/* harmony import */ var prismjs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prismjs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_plugins_datasource_loki_components_useLokiLabels__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/plugins/datasource/loki/components/useLokiLabels */ "./public/app/plugins/datasource/loki/components/useLokiLabels.ts");
/* harmony import */ var app_core_hooks_useRefMounted__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/hooks/useRefMounted */ "./public/app/core/hooks/useRefMounted.ts");
var _this = undefined;





var PRISM_SYNTAX = 'promql';
/**
 *
 * @param languageProvider
 * @description Initializes given language provider, exposes Loki syntax and enables loading label option values
 */
var useLokiSyntax = function (languageProvider, datasourceStatus, absoluteRange) {
    var mounted = Object(app_core_hooks_useRefMounted__WEBPACK_IMPORTED_MODULE_4__["useRefMounted"])();
    // State
    var _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(false), 2), languageProviderInitialized = _a[0], setLanguageProviderInitilized = _a[1];
    var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(null), 2), syntax = _b[0], setSyntax = _b[1];
    /**
     * Holds information about currently selected option from rc-cascader to perform effect
     * that loads option values not fetched yet. Based on that useLokiLabels hook decides whether or not
     * the option requires additional data fetching
     */
    var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](Object(react__WEBPACK_IMPORTED_MODULE_1__["useState"])(), 2), activeOption = _c[0], setActiveOption = _c[1];
    var _d = Object(app_plugins_datasource_loki_components_useLokiLabels__WEBPACK_IMPORTED_MODULE_3__["useLokiLabels"])(languageProvider, languageProviderInitialized, activeOption, absoluteRange, datasourceStatus), logLabelOptions = _d.logLabelOptions, setLogLabelOptions = _d.setLogLabelOptions, refreshLabels = _d.refreshLabels;
    // Async
    var initializeLanguageProvider = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
            switch (_a.label) {
                case 0:
                    languageProvider.initialRange = absoluteRange;
                    return [4 /*yield*/, languageProvider.start()];
                case 1:
                    _a.sent();
                    prismjs__WEBPACK_IMPORTED_MODULE_2___default.a.languages[PRISM_SYNTAX] = languageProvider.getSyntax();
                    if (mounted.current) {
                        setLogLabelOptions(languageProvider.logLabelOptions);
                        setSyntax(languageProvider.getSyntax());
                        setLanguageProviderInitilized(true);
                    }
                    return [2 /*return*/];
            }
        });
    }); };
    // Effects
    Object(react__WEBPACK_IMPORTED_MODULE_1__["useEffect"])(function () {
        initializeLanguageProvider();
    }, []);
    return {
        isSyntaxReady: languageProviderInitialized,
        syntax: syntax,
        logLabelOptions: logLabelOptions,
        setActiveOption: setActiveOption,
        refreshLabels: refreshLabels,
    };
};


/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/Aggregations.tsx":
/*!*******************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/Aggregations.tsx ***!
  \*******************************************************************************/
/*! exports provided: Aggregations */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Aggregations", function() { return Aggregations; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/components/Select/MetricSelect */ "./public/app/core/components/Select/MetricSelect.tsx");
/* harmony import */ var _functions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../functions */ "./public/app/plugins/datasource/stackdriver/functions.ts");




var Aggregations = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Aggregations, _super);
    function Aggregations() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            aggOptions: [],
            displayAdvancedOptions: false,
        };
        _this.onToggleDisplayAdvanced = function () {
            _this.setState(function (state) { return ({
                displayAdvancedOptions: !state.displayAdvancedOptions,
            }); });
        };
        return _this;
    }
    Aggregations.prototype.componentDidMount = function () {
        this.setAggOptions(this.props);
    };
    Aggregations.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        this.setAggOptions(nextProps);
    };
    Aggregations.prototype.setAggOptions = function (_a) {
        var metricDescriptor = _a.metricDescriptor;
        var aggOptions = [];
        if (metricDescriptor) {
            aggOptions = [
                {
                    label: 'Aggregations',
                    expanded: true,
                    options: Object(_functions__WEBPACK_IMPORTED_MODULE_3__["getAggregationOptionsByMetric"])(metricDescriptor.valueType, metricDescriptor.metricKind).map(function (a) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, a, { label: a.text })); }),
                },
            ];
        }
        this.setState({ aggOptions: aggOptions });
    };
    Aggregations.prototype.render = function () {
        var _a = this.state, displayAdvancedOptions = _a.displayAdvancedOptions, aggOptions = _a.aggOptions;
        var _b = this.props, templateSrv = _b.templateSrv, onChange = _b.onChange, crossSeriesReducer = _b.crossSeriesReducer;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label query-keyword width-9" }, "Aggregation"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_2__["MetricSelect"], { onChange: onChange, value: crossSeriesReducer, variables: templateSrv.variables, options: aggOptions, placeholder: "Select Reducer", className: "width-15" })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label gf-form-label--grow" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { onClick: this.onToggleDisplayAdvanced },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-" + (displayAdvancedOptions ? 'down' : 'right') }),
                                " Advanced Options"))))),
            this.props.children(this.state.displayAdvancedOptions)));
    };
    return Aggregations;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/AliasBy.tsx":
/*!**************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/AliasBy.tsx ***!
  \**************************************************************************/
/*! exports provided: AliasBy */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AliasBy", function() { return AliasBy; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var AliasBy = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AliasBy, _super);
    function AliasBy(props) {
        var _this = _super.call(this, props) || this;
        _this.onChange = function (e) {
            _this.setState({ value: e.target.value });
            _this.propagateOnChange(e.target.value);
        };
        _this.propagateOnChange = Object(lodash__WEBPACK_IMPORTED_MODULE_2__["debounce"])(_this.props.onChange, 500);
        _this.state = { value: '' };
        return _this;
    }
    AliasBy.prototype.componentDidMount = function () {
        this.setState({ value: this.props.value });
    };
    AliasBy.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        if (nextProps.value !== this.props.value) {
            this.setState({ value: nextProps.value });
        }
    };
    AliasBy.prototype.render = function () {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label query-keyword width-9" }, "Alias By"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["Input"], { type: "text", className: "gf-form-input width-24", value: this.state.value, onChange: this.onChange })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label gf-form-label--grow" })))));
    };
    return AliasBy;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/AlignmentPeriods.tsx":
/*!***********************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/AlignmentPeriods.tsx ***!
  \***********************************************************************************/
/*! exports provided: AlignmentPeriods */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlignmentPeriods", function() { return AlignmentPeriods; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/components/Select/MetricSelect */ "./public/app/core/components/Select/MetricSelect.tsx");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../constants */ "./public/app/plugins/datasource/stackdriver/constants.ts");





var AlignmentPeriods = function (_a) {
    var alignmentPeriod = _a.alignmentPeriod, templateSrv = _a.templateSrv, onChange = _a.onChange, perSeriesAligner = _a.perSeriesAligner, usedAlignmentPeriod = _a.usedAlignmentPeriod;
    var alignment = _constants__WEBPACK_IMPORTED_MODULE_4__["alignOptions"].find(function (ap) { return ap.value === templateSrv.replace(perSeriesAligner); });
    var formatAlignmentText = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_2__["default"].secondsToHms(usedAlignmentPeriod) + " interval (" + (alignment ? alignment.text : '') + ")";
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label query-keyword width-9" }, "Alignment Period"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_3__["MetricSelect"], { onChange: onChange, value: alignmentPeriod, variables: templateSrv.variables, options: [
                        {
                            label: 'Alignment options',
                            expanded: true,
                            options: _constants__WEBPACK_IMPORTED_MODULE_4__["alignmentPeriods"].map(function (ap) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, ap, { label: ap.text })); }),
                        },
                    ], placeholder: "Select Alignment", className: "width-15" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" }, usedAlignmentPeriod && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label gf-form-label--grow" }, formatAlignmentText)))));
};


/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/Alignments.tsx":
/*!*****************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/Alignments.tsx ***!
  \*****************************************************************************/
/*! exports provided: Alignments */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Alignments", function() { return Alignments; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/components/Select/MetricSelect */ "./public/app/core/components/Select/MetricSelect.tsx");


var Alignments = function (_a) {
    var perSeriesAligner = _a.perSeriesAligner, templateSrv = _a.templateSrv, onChange = _a.onChange, alignOptions = _a.alignOptions;
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null,
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form offset-width-9" },
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("label", { className: "gf-form-label query-keyword width-15" }, "Aligner"),
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_1__["MetricSelect"], { onChange: onChange, value: perSeriesAligner, variables: templateSrv.variables, options: alignOptions, placeholder: "Select Alignment", className: "width-15" })))));
};


/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/AnnotationQueryEditor.tsx":
/*!****************************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/AnnotationQueryEditor.tsx ***!
  \****************************************************************************************/
/*! exports provided: AnnotationQueryEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnnotationQueryEditor", function() { return AnnotationQueryEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _Metrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Metrics */ "./public/app/plugins/datasource/stackdriver/components/Metrics.tsx");
/* harmony import */ var _Filter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Filter */ "./public/app/plugins/datasource/stackdriver/components/Filter.tsx");
/* harmony import */ var _AnnotationsHelp__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./AnnotationsHelp */ "./public/app/plugins/datasource/stackdriver/components/AnnotationsHelp.tsx");






var DefaultTarget = {
    defaultProject: 'loading project...',
    metricType: '',
    filters: [],
    metricKind: '',
    valueType: '',
    refId: 'annotationQuery',
    title: '',
    text: '',
};
var AnnotationQueryEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnnotationQueryEditor, _super);
    function AnnotationQueryEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = DefaultTarget;
        _this.onMetricTypeChange = function (_a) {
            var valueType = _a.valueType, metricKind = _a.metricKind, type = _a.type, unit = _a.unit;
            var onQueryChange = _this.props.onQueryChange;
            _this.setState({
                metricType: type,
                unit: unit,
                valueType: valueType,
                metricKind: metricKind,
            }, function () {
                onQueryChange(_this.state);
            });
        };
        return _this;
    }
    AnnotationQueryEditor.prototype.componentDidMount = function () {
        this.setState(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.props.target));
    };
    AnnotationQueryEditor.prototype.onChange = function (prop, value) {
        var _a;
        var _this = this;
        this.setState((_a = {}, _a[prop] = value, _a), function () {
            _this.props.onQueryChange(_this.state);
        });
    };
    AnnotationQueryEditor.prototype.render = function () {
        var _this = this;
        var _a = this.state, defaultProject = _a.defaultProject, metricType = _a.metricType, filters = _a.filters, refId = _a.refId, title = _a.title, text = _a.text;
        var _b = this.props, datasource = _b.datasource, templateSrv = _b.templateSrv;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Metrics__WEBPACK_IMPORTED_MODULE_3__["Metrics"], { defaultProject: defaultProject, metricType: metricType, templateSrv: templateSrv, datasource: datasource, onChange: this.onMetricTypeChange }, function (metric) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Filter__WEBPACK_IMPORTED_MODULE_4__["Filter"], { filtersChanged: function (value) { return _this.onChange('filters', value); }, filters: filters, refId: refId, hideGroupBys: true, templateSrv: templateSrv, datasource: datasource, metricType: metric ? metric.type : '' }))); }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label query-keyword width-9" }, "Title"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { type: "text", className: "gf-form-input width-20", value: title, onChange: function (e) { return _this.onChange('title', e.target.value); } })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label query-keyword width-9" }, "Text"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { type: "text", className: "gf-form-input width-20", value: text, onChange: function (e) { return _this.onChange('text', e.target.value); } })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label gf-form-label--grow" }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AnnotationsHelp__WEBPACK_IMPORTED_MODULE_5__["AnnotationsHelp"], null)));
    };
    return AnnotationQueryEditor;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/AnnotationsHelp.tsx":
/*!**********************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/AnnotationsHelp.tsx ***!
  \**********************************************************************************/
/*! exports provided: AnnotationsHelp */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnnotationsHelp", function() { return AnnotationsHelp; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var AnnotationsHelp = function () {
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "gf-form grafana-info-box", style: { padding: 0 } },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("pre", { className: "gf-form-pre alert alert-info", style: { marginRight: 0 } },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h5", null, "Annotation Query Format"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                "An annotation is an event that is overlaid on top of graphs. Annotation rendering is expensive so it is important to limit the number of rows returned.",
                ' '),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "The Title and Text fields support templating and can use data returned from the query. For example, the Title field could have the following text:"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{metric.type}}',
                " has value: ", "" + '{{metric.value}}'),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                "Example Result: ",
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "monitoring.googleapis.com/uptime_check/http_status has this value: 502")),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("label", null, "Patterns:"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{metric.value}}'),
                " = value of the metric/point"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{metric.type}}'),
                " = metric type e.g. compute.googleapis.com/instance/cpu/usage_time"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{metric.name}}'),
                " = name part of metric e.g. instance/cpu/usage_time"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{metric.service}}'),
                " = service part of metric e.g. compute"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{metric.label.label_name}}'),
                " = Metric label metadata e.g. metric.label.instance_name"),
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null,
                react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("code", null, "" + '{{resource.label.label_name}}'),
                " = Resource label metadata e.g. resource.label.zone"))));
};


/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/Filter.tsx":
/*!*************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/Filter.tsx ***!
  \*************************************************************************/
/*! exports provided: Filter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Filter", function() { return Filter; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var _query_filter_ctrl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../query_filter_ctrl */ "./public/app/plugins/datasource/stackdriver/query_filter_ctrl.ts");





var labelData = {
    metricLabels: {},
    resourceLabels: {},
    resourceTypes: [],
};
var Filter = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Filter, _super);
    function Filter() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Filter.prototype.componentDidMount = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var _a, groupBys, filters, hideGroupBys, loader, filtersChanged, groupBysChanged, scopeProps, loading, template;
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
                if (!this.element) {
                    return [2 /*return*/];
                }
                _a = this.props, groupBys = _a.groupBys, filters = _a.filters, hideGroupBys = _a.hideGroupBys;
                loader = Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_3__["getAngularLoader"])();
                filtersChanged = function (filters) {
                    _this.props.filtersChanged(filters);
                };
                groupBysChanged = function (groupBys) {
                    _this.props.groupBysChanged(groupBys);
                };
                scopeProps = {
                    loading: null,
                    labelData: labelData,
                    groupBys: groupBys,
                    filters: filters,
                    filtersChanged: filtersChanged,
                    groupBysChanged: groupBysChanged,
                    hideGroupBys: hideGroupBys,
                };
                loading = this.loadLabels(scopeProps);
                scopeProps.loading = loading;
                template = "<stackdriver-filter\n                        filters=\"filters\"\n                        group-bys=\"groupBys\"\n                        label-data=\"labelData\"\n                        loading=\"loading\"\n                        filters-changed=\"filtersChanged(filters)\"\n                        group-bys-changed=\"groupBysChanged(groupBys)\"\n                        hide-group-bys=\"hideGroupBys\"/>";
                this.component = loader.load(this.element, scopeProps, template);
                return [2 /*return*/];
            });
        });
    };
    Filter.prototype.componentDidUpdate = function (prevProps) {
        if (!this.element) {
            return;
        }
        var scope = this.component.getScope();
        if (prevProps.metricType !== this.props.metricType) {
            scope.loading = this.loadLabels(scope);
        }
        scope.filters = this.props.filters;
        scope.groupBys = this.props.groupBys;
    };
    Filter.prototype.componentWillUnmount = function () {
        if (this.component) {
            this.component.destroy();
        }
    };
    Filter.prototype.loadLabels = function (scope) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
                        var meta, error_1;
                        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    _a.trys.push([0, 4, , 5]);
                                    if (!!this.props.metricType) return [3 /*break*/, 1];
                                    scope.labelData = labelData;
                                    return [3 /*break*/, 3];
                                case 1: return [4 /*yield*/, this.props.datasource.getLabels(this.props.metricType, this.props.refId)];
                                case 2:
                                    meta = (_a.sent()).meta;
                                    scope.labelData = meta;
                                    _a.label = 3;
                                case 3:
                                    resolve();
                                    return [3 /*break*/, 5];
                                case 4:
                                    error_1 = _a.sent();
                                    app_core_app_events__WEBPACK_IMPORTED_MODULE_2__["default"].emit('alert-error', ['Error', 'Error loading metric labels for ' + this.props.metricType]);
                                    scope.labelData = labelData;
                                    resolve();
                                    return [3 /*break*/, 5];
                                case 5: return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    Filter.prototype.render = function () {
        var _this = this;
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { ref: function (element) { return (_this.element = element); }, style: { width: '100%' } });
    };
    return Filter;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/Help.tsx":
/*!***********************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/Help.tsx ***!
  \***********************************************************************/
/*! exports provided: Help */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Help", function() { return Help; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Project__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Project */ "./public/app/plugins/datasource/stackdriver/components/Project.tsx");



var Help = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Help, _super);
    function Help() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            displayHelp: false,
            displaRawQuery: false,
        };
        _this.onHelpClicked = function () {
            _this.setState({ displayHelp: !_this.state.displayHelp });
        };
        _this.onRawQueryClicked = function () {
            _this.setState({ displaRawQuery: !_this.state.displaRawQuery });
        };
        return _this;
    }
    Help.prototype.shouldComponentUpdate = function (nextProps) {
        return nextProps.metricDescriptor !== null;
    };
    Help.prototype.render = function () {
        var _a = this.state, displayHelp = _a.displayHelp, displaRawQuery = _a.displaRawQuery;
        var _b = this.props, datasource = _b.datasource, rawQuery = _b.rawQuery, lastQueryError = _b.lastQueryError;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Project__WEBPACK_IMPORTED_MODULE_2__["Project"], { datasource: datasource }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form", onClick: this.onHelpClicked },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label query-keyword pointer" },
                        "Show Help ",
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-" + (displayHelp ? 'down' : 'right') }))),
                rawQuery && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form", onClick: this.onRawQueryClicked },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", { className: "gf-form-label query-keyword" },
                        "Raw Query ",
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-caret-" + (displaRawQuery ? 'down' : 'right'), "ng-show": "ctrl.showHelp" })))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label gf-form-label--grow" }))),
            rawQuery && displaRawQuery && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("pre", { className: "gf-form-pre" }, rawQuery))),
            displayHelp && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form grafana-info-box", style: { padding: 0 } },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("pre", { className: "gf-form-pre alert alert-info", style: { marginRight: 0 } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", null, "Alias Patterns"),
                    "Format the legend keys any way you want by using alias patterns. Format the legend keys any way you want by using alias patterns.",
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                    " ",
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                    "Example:",
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{metricDescriptor.name}} - {{metricDescriptor.label.instance_name}}'),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                    "Result: \u00A0\u00A0",
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "cpu/usage_time - server1-europe-west-1"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("strong", null, "Patterns"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", null,
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{metricDescriptor.type}}'),
                            " = metric type e.g. compute.googleapis.com/instance/cpu/usage_time"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{metricDescriptor.name}}'),
                            " = name part of metric e.g. instance/cpu/usage_time"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{metricDescriptor.service}}'),
                            " = service part of metric e.g. compute"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{metricDescriptor.label.label_name}}'),
                            " = Metric label metadata e.g. metricDescriptor.label.instance_name"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{resource.label.label_name}}'),
                            " = Resource label metadata e.g. resource.label.zone"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", null,
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("code", null, "" + '{{bucket}}'),
                            " = bucket boundary for distribution metrics when using a heatmap in Grafana"))))),
            lastQueryError && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("pre", { className: "gf-form-pre alert alert-error" }, lastQueryError)))));
    };
    return Help;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/Metrics.tsx":
/*!**************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/Metrics.tsx ***!
  \**************************************************************************/
/*! exports provided: Metrics */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Metrics", function() { return Metrics; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/components/Select/MetricSelect */ "./public/app/core/components/Select/MetricSelect.tsx");





var Metrics = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Metrics, _super);
    function Metrics(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            metricDescriptors: [],
            metrics: [],
            services: [],
            service: '',
            metric: '',
            metricDescriptor: null,
            defaultProject: '',
        };
        _this.onServiceChange = function (service) {
            var metricDescriptors = _this.state.metricDescriptors;
            var _a = _this.props, templateSrv = _a.templateSrv, metricType = _a.metricType;
            var metrics = metricDescriptors
                .filter(function (m) { return m.service === templateSrv.replace(service); })
                .map(function (m) { return ({
                service: m.service,
                value: m.type,
                label: m.displayName,
                description: m.description,
            }); });
            _this.setState({ service: service, metrics: metrics });
            if (metrics.length > 0 && !metrics.some(function (m) { return m.value === templateSrv.replace(metricType); })) {
                _this.onMetricTypeChange(metrics[0].value);
            }
        };
        _this.onMetricTypeChange = function (value) {
            var metricDescriptor = _this.getSelectedMetricDescriptor(value);
            _this.setState({ metricDescriptor: metricDescriptor });
            _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, metricDescriptor, { type: value }));
        };
        return _this;
    }
    Metrics.prototype.componentDidMount = function () {
        var _this = this;
        this.setState({ defaultProject: this.props.defaultProject }, function () {
            _this.getCurrentProject()
                .then(_this.loadMetricDescriptors.bind(_this))
                .then(_this.initializeServiceAndMetrics.bind(_this));
        });
    };
    Metrics.prototype.getCurrentProject = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve, reject) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
                        var defaultProject, error_1;
                        return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    _a.trys.push([0, 3, , 4]);
                                    if (!(!this.state.defaultProject || this.state.defaultProject === 'loading project...')) return [3 /*break*/, 2];
                                    return [4 /*yield*/, this.props.datasource.getDefaultProject()];
                                case 1:
                                    defaultProject = _a.sent();
                                    this.setState({ defaultProject: defaultProject });
                                    _a.label = 2;
                                case 2:
                                    resolve(this.state.defaultProject);
                                    return [3 /*break*/, 4];
                                case 3:
                                    error_1 = _a.sent();
                                    app_core_app_events__WEBPACK_IMPORTED_MODULE_3__["default"].emit('ds-request-error', error_1);
                                    reject();
                                    return [3 /*break*/, 4];
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    Metrics.prototype.loadMetricDescriptors = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var metricDescriptors;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.state.defaultProject !== 'loading project...')) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.props.datasource.getMetricTypes(this.state.defaultProject)];
                    case 1:
                        metricDescriptors = _a.sent();
                        this.setState({ metricDescriptors: metricDescriptors });
                        return [2 /*return*/, metricDescriptors];
                    case 2: return [2 /*return*/, []];
                }
            });
        });
    };
    Metrics.prototype.initializeServiceAndMetrics = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var metricDescriptors, services, metrics, service, metricDescriptor;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                metricDescriptors = this.state.metricDescriptors;
                services = this.getServicesList(metricDescriptors);
                metrics = this.getMetricsList(metricDescriptors);
                service = metrics.length > 0 ? metrics[0].service : '';
                metricDescriptor = this.getSelectedMetricDescriptor(this.props.metricType);
                this.setState({ metricDescriptors: metricDescriptors, services: services, metrics: metrics, service: service, metricDescriptor: metricDescriptor });
                return [2 /*return*/];
            });
        });
    };
    Metrics.prototype.getSelectedMetricDescriptor = function (metricType) {
        var _this = this;
        return this.state.metricDescriptors.find(function (md) { return md.type === _this.props.templateSrv.replace(metricType); });
    };
    Metrics.prototype.getMetricsList = function (metricDescriptors) {
        var selectedMetricDescriptor = this.getSelectedMetricDescriptor(this.props.metricType);
        if (!selectedMetricDescriptor) {
            return [];
        }
        var metricsByService = metricDescriptors
            .filter(function (m) { return m.service === selectedMetricDescriptor.service; })
            .map(function (m) { return ({
            service: m.service,
            value: m.type,
            label: m.displayName,
            description: m.description,
        }); });
        return metricsByService;
    };
    Metrics.prototype.getServicesList = function (metricDescriptors) {
        var services = metricDescriptors.map(function (m) { return ({
            value: m.service,
            label: lodash__WEBPACK_IMPORTED_MODULE_2___default.a.startCase(m.serviceShortName),
        }); });
        return services.length > 0 ? lodash__WEBPACK_IMPORTED_MODULE_2___default.a.uniqBy(services, function (s) { return s.value; }) : [];
    };
    Metrics.prototype.getTemplateVariablesGroup = function () {
        return {
            label: 'Template Variables',
            options: this.props.templateSrv.variables.map(function (v) { return ({
                label: "$" + v.name,
                value: "$" + v.name,
            }); }),
        };
    };
    Metrics.prototype.render = function () {
        var _a = this.state, services = _a.services, service = _a.service, metrics = _a.metrics;
        var _b = this.props, metricType = _b.metricType, templateSrv = _b.templateSrv;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label width-9 query-keyword" }, "Service"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_4__["MetricSelect"], { onChange: this.onServiceChange, value: service, options: services, isSearchable: false, placeholder: "Select Services", className: "width-15" })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label gf-form-label--grow" }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label width-9 query-keyword" }, "Metric"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_Select_MetricSelect__WEBPACK_IMPORTED_MODULE_4__["MetricSelect"], { onChange: this.onMetricTypeChange, value: metricType, variables: templateSrv.variables, options: [
                            {
                                label: 'Metrics',
                                expanded: true,
                                options: metrics,
                            },
                        ], placeholder: "Select Metric", className: "width-26" })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form gf-form--grow" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label gf-form-label--grow" }))),
            this.props.children(this.state.metricDescriptor)));
    };
    return Metrics;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/Project.tsx":
/*!**************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/Project.tsx ***!
  \**************************************************************************/
/*! exports provided: Project */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Project", function() { return Project; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");



var Project = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Project, _super);
    function Project() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            projectName: 'Loading project...',
        };
        return _this;
    }
    Project.prototype.componentDidMount = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var projectName;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.props.datasource.getDefaultProject()];
                    case 1:
                        projectName = _a.sent();
                        this.setState({ projectName: projectName });
                        return [2 /*return*/];
                }
            });
        });
    };
    Project.prototype.render = function () {
        var projectName = this.state.projectName;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label width-9 query-keyword" }, "Project"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input width-15", disabled: true, type: "text", value: projectName })));
    };
    return Project;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/components/QueryEditor.tsx":
/*!******************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/components/QueryEditor.tsx ***!
  \******************************************************************************/
/*! exports provided: DefaultTarget, QueryEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultTarget", function() { return DefaultTarget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryEditor", function() { return QueryEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Metrics__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Metrics */ "./public/app/plugins/datasource/stackdriver/components/Metrics.tsx");
/* harmony import */ var _Filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Filter */ "./public/app/plugins/datasource/stackdriver/components/Filter.tsx");
/* harmony import */ var _Aggregations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Aggregations */ "./public/app/plugins/datasource/stackdriver/components/Aggregations.tsx");
/* harmony import */ var _Alignments__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Alignments */ "./public/app/plugins/datasource/stackdriver/components/Alignments.tsx");
/* harmony import */ var _AlignmentPeriods__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./AlignmentPeriods */ "./public/app/plugins/datasource/stackdriver/components/AlignmentPeriods.tsx");
/* harmony import */ var _AliasBy__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./AliasBy */ "./public/app/plugins/datasource/stackdriver/components/AliasBy.tsx");
/* harmony import */ var _Help__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Help */ "./public/app/plugins/datasource/stackdriver/components/Help.tsx");
/* harmony import */ var _functions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../functions */ "./public/app/plugins/datasource/stackdriver/functions.ts");










var DefaultTarget = {
    defaultProject: 'loading project...',
    metricType: '',
    metricKind: '',
    valueType: '',
    refId: '',
    service: '',
    unit: '',
    crossSeriesReducer: 'REDUCE_MEAN',
    alignmentPeriod: 'stackdriver-auto',
    perSeriesAligner: 'ALIGN_MEAN',
    groupBys: [],
    filters: [],
    aliasBy: '',
    alignOptions: [],
    lastQuery: '',
    lastQueryError: '',
    usedAlignmentPeriod: '',
};
var QueryEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QueryEditor, _super);
    function QueryEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = DefaultTarget;
        _this.onMetricTypeChange = function (_a) {
            var valueType = _a.valueType, metricKind = _a.metricKind, type = _a.type, unit = _a.unit;
            var _b = _this.props, templateSrv = _b.templateSrv, onQueryChange = _b.onQueryChange, onExecuteQuery = _b.onExecuteQuery;
            var _c = Object(_functions__WEBPACK_IMPORTED_MODULE_9__["getAlignmentPickerData"])({ valueType: valueType, metricKind: metricKind, perSeriesAligner: _this.state.perSeriesAligner }, templateSrv), perSeriesAligner = _c.perSeriesAligner, alignOptions = _c.alignOptions;
            _this.setState({
                alignOptions: alignOptions,
                perSeriesAligner: perSeriesAligner,
                metricType: type,
                unit: unit,
                valueType: valueType,
                metricKind: metricKind,
            }, function () {
                onQueryChange(_this.state);
                onExecuteQuery();
            });
        };
        return _this;
    }
    QueryEditor.prototype.componentDidMount = function () {
        var _a = this.props, events = _a.events, target = _a.target, templateSrv = _a.templateSrv;
        events.on('data-received', this.onDataReceived.bind(this));
        events.on('data-error', this.onDataError.bind(this));
        var _b = Object(_functions__WEBPACK_IMPORTED_MODULE_9__["getAlignmentPickerData"])(target, templateSrv), perSeriesAligner = _b.perSeriesAligner, alignOptions = _b.alignOptions;
        this.setState(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.props.target, { alignOptions: alignOptions,
            perSeriesAligner: perSeriesAligner }));
    };
    QueryEditor.prototype.componentWillUnmount = function () {
        this.props.events.off('data-received', this.onDataReceived);
        this.props.events.off('data-error', this.onDataError);
    };
    QueryEditor.prototype.onDataReceived = function (dataList) {
        var _this = this;
        var series = dataList.find(function (item) { return item.refId === _this.props.target.refId; });
        if (series) {
            this.setState({
                lastQuery: decodeURIComponent(series.meta.rawQuery),
                lastQueryError: '',
                usedAlignmentPeriod: series.meta.alignmentPeriod,
            });
        }
    };
    QueryEditor.prototype.onDataError = function (err) {
        var lastQuery;
        var lastQueryError;
        if (err.data && err.data.error) {
            lastQueryError = this.props.datasource.formatStackdriverError(err);
        }
        else if (err.data && err.data.results) {
            var queryRes = err.data.results[this.props.target.refId];
            lastQuery = decodeURIComponent(queryRes.meta.rawQuery);
            if (queryRes && queryRes.error) {
                try {
                    lastQueryError = JSON.parse(queryRes.error).error.message;
                }
                catch (_a) {
                    lastQueryError = queryRes.error;
                }
            }
        }
        this.setState({ lastQuery: lastQuery, lastQueryError: lastQueryError });
    };
    QueryEditor.prototype.onPropertyChange = function (prop, value) {
        var _a;
        var _this = this;
        this.setState((_a = {}, _a[prop] = value, _a), function () {
            _this.props.onQueryChange(_this.state);
            _this.props.onExecuteQuery();
        });
    };
    QueryEditor.prototype.render = function () {
        var _this = this;
        var _a = this.state, usedAlignmentPeriod = _a.usedAlignmentPeriod, defaultProject = _a.defaultProject, metricType = _a.metricType, crossSeriesReducer = _a.crossSeriesReducer, groupBys = _a.groupBys, filters = _a.filters, perSeriesAligner = _a.perSeriesAligner, alignOptions = _a.alignOptions, alignmentPeriod = _a.alignmentPeriod, aliasBy = _a.aliasBy, lastQuery = _a.lastQuery, lastQueryError = _a.lastQueryError, refId = _a.refId;
        var _b = this.props, datasource = _b.datasource, templateSrv = _b.templateSrv;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Metrics__WEBPACK_IMPORTED_MODULE_2__["Metrics"], { defaultProject: defaultProject, metricType: metricType, templateSrv: templateSrv, datasource: datasource, onChange: this.onMetricTypeChange }, function (metric) { return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Filter__WEBPACK_IMPORTED_MODULE_3__["Filter"], { filtersChanged: function (value) { return _this.onPropertyChange('filters', value); }, groupBysChanged: function (value) { return _this.onPropertyChange('groupBys', value); }, filters: filters, groupBys: groupBys, refId: refId, hideGroupBys: false, templateSrv: templateSrv, datasource: datasource, metricType: metric ? metric.type : '' }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Aggregations__WEBPACK_IMPORTED_MODULE_4__["Aggregations"], { metricDescriptor: metric, templateSrv: templateSrv, crossSeriesReducer: crossSeriesReducer, groupBys: groupBys, onChange: function (value) { return _this.onPropertyChange('crossSeriesReducer', value); } }, function (displayAdvancedOptions) {
                    return displayAdvancedOptions && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Alignments__WEBPACK_IMPORTED_MODULE_5__["Alignments"], { alignOptions: alignOptions, templateSrv: templateSrv, perSeriesAligner: perSeriesAligner, onChange: function (value) { return _this.onPropertyChange('perSeriesAligner', value); } }));
                }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AlignmentPeriods__WEBPACK_IMPORTED_MODULE_6__["AlignmentPeriods"], { templateSrv: templateSrv, alignmentPeriod: alignmentPeriod, perSeriesAligner: perSeriesAligner, usedAlignmentPeriod: usedAlignmentPeriod, onChange: function (value) { return _this.onPropertyChange('alignmentPeriod', value); } }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_AliasBy__WEBPACK_IMPORTED_MODULE_7__["AliasBy"], { value: aliasBy, onChange: function (value) { return _this.onPropertyChange('aliasBy', value); } }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_Help__WEBPACK_IMPORTED_MODULE_8__["Help"], { datasource: datasource, rawQuery: lastQuery, lastQueryError: lastQueryError }))); })));
    };
    return QueryEditor;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/constants.ts":
/*!****************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/constants.ts ***!
  \****************************************************************/
/*! exports provided: MetricKind, ValueTypes, alignOptions, aggOptions, alignmentPeriods, stackdriverUnitMappings */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetricKind", function() { return MetricKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueTypes", function() { return ValueTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignOptions", function() { return alignOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "aggOptions", function() { return aggOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignmentPeriods", function() { return alignmentPeriods; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stackdriverUnitMappings", function() { return stackdriverUnitMappings; });
var MetricKind;
(function (MetricKind) {
    MetricKind["METRIC_KIND_UNSPECIFIED"] = "METRIC_KIND_UNSPECIFIED";
    MetricKind["GAUGE"] = "GAUGE";
    MetricKind["DELTA"] = "DELTA";
    MetricKind["CUMULATIVE"] = "CUMULATIVE";
})(MetricKind || (MetricKind = {}));
var ValueTypes;
(function (ValueTypes) {
    ValueTypes["VALUE_TYPE_UNSPECIFIED"] = "VALUE_TYPE_UNSPECIFIED";
    ValueTypes["BOOL"] = "BOOL";
    ValueTypes["INT64"] = "INT64";
    ValueTypes["DOUBLE"] = "DOUBLE";
    ValueTypes["STRING"] = "STRING";
    ValueTypes["DISTRIBUTION"] = "DISTRIBUTION";
    ValueTypes["MONEY"] = "MONEY";
})(ValueTypes || (ValueTypes = {}));
var alignOptions = [
    {
        text: 'delta',
        value: 'ALIGN_DELTA',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.CUMULATIVE, MetricKind.DELTA],
    },
    {
        text: 'rate',
        value: 'ALIGN_RATE',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.CUMULATIVE, MetricKind.DELTA],
    },
    {
        text: 'interpolate',
        value: 'ALIGN_INTERPOLATE',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE],
    },
    {
        text: 'next older',
        value: 'ALIGN_NEXT_OLDER',
        valueTypes: [
            ValueTypes.INT64,
            ValueTypes.DOUBLE,
            ValueTypes.MONEY,
            ValueTypes.DISTRIBUTION,
            ValueTypes.STRING,
            ValueTypes.VALUE_TYPE_UNSPECIFIED,
            ValueTypes.BOOL,
        ],
        metricKinds: [MetricKind.GAUGE],
    },
    {
        text: 'min',
        value: 'ALIGN_MIN',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'max',
        value: 'ALIGN_MAX',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'mean',
        value: 'ALIGN_MEAN',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'count',
        value: 'ALIGN_COUNT',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.BOOL],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'sum',
        value: 'ALIGN_SUM',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'stddev',
        value: 'ALIGN_STDDEV',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'count true',
        value: 'ALIGN_COUNT_TRUE',
        valueTypes: [ValueTypes.BOOL],
        metricKinds: [MetricKind.GAUGE],
    },
    {
        text: 'count false',
        value: 'ALIGN_COUNT_FALSE',
        valueTypes: [ValueTypes.BOOL],
        metricKinds: [MetricKind.GAUGE],
    },
    {
        text: 'fraction true',
        value: 'ALIGN_FRACTION_TRUE',
        valueTypes: [ValueTypes.BOOL],
        metricKinds: [MetricKind.GAUGE],
    },
    {
        text: 'percentile 99',
        value: 'ALIGN_PERCENTILE_99',
        valueTypes: [ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'percentile 95',
        value: 'ALIGN_PERCENTILE_95',
        valueTypes: [ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'percentile 50',
        value: 'ALIGN_PERCENTILE_50',
        valueTypes: [ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'percentile 05',
        value: 'ALIGN_PERCENTILE_05',
        valueTypes: [ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'percent change',
        value: 'ALIGN_PERCENT_CHANGE',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
];
var aggOptions = [
    {
        text: 'none',
        value: 'REDUCE_NONE',
        valueTypes: [
            ValueTypes.INT64,
            ValueTypes.DOUBLE,
            ValueTypes.MONEY,
            ValueTypes.DISTRIBUTION,
            ValueTypes.BOOL,
            ValueTypes.STRING,
        ],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE, MetricKind.METRIC_KIND_UNSPECIFIED],
    },
    {
        text: 'mean',
        value: 'REDUCE_MEAN',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'min',
        value: 'REDUCE_MIN',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE, MetricKind.METRIC_KIND_UNSPECIFIED],
    },
    {
        text: 'max',
        value: 'REDUCE_MAX',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE, MetricKind.METRIC_KIND_UNSPECIFIED],
    },
    {
        text: 'sum',
        value: 'REDUCE_SUM',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE, MetricKind.METRIC_KIND_UNSPECIFIED],
    },
    {
        text: 'std. dev.',
        value: 'REDUCE_STDDEV',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE, MetricKind.METRIC_KIND_UNSPECIFIED],
    },
    {
        text: 'count',
        value: 'REDUCE_COUNT',
        valueTypes: [
            ValueTypes.INT64,
            ValueTypes.DOUBLE,
            ValueTypes.MONEY,
            ValueTypes.DISTRIBUTION,
            ValueTypes.BOOL,
            ValueTypes.STRING,
        ],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE],
    },
    {
        text: 'count true',
        value: 'REDUCE_COUNT_TRUE',
        valueTypes: [ValueTypes.BOOL],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: 'count false',
        value: 'REDUCE_COUNT_FALSE',
        valueTypes: [ValueTypes.BOOL],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA],
    },
    {
        text: '99th percentile',
        value: 'REDUCE_PERCENTILE_99',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE],
    },
    {
        text: '95th percentile',
        value: 'REDUCE_PERCENTILE_95',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE],
    },
    {
        text: '50th percentile',
        value: 'REDUCE_PERCENTILE_50',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE],
    },
    {
        text: '5th percentile',
        value: 'REDUCE_PERCENTILE_05',
        valueTypes: [ValueTypes.INT64, ValueTypes.DOUBLE, ValueTypes.MONEY, ValueTypes.DISTRIBUTION],
        metricKinds: [MetricKind.GAUGE, MetricKind.DELTA, MetricKind.CUMULATIVE],
    },
];
var alignmentPeriods = [
    { text: 'grafana auto', value: 'grafana-auto' },
    { text: 'stackdriver auto', value: 'stackdriver-auto' },
    { text: '1m', value: '+60s' },
    { text: '2m', value: '+120s' },
    { text: '5m', value: '+300s' },
    { text: '10m', value: '+600s' },
    { text: '30m', value: '+1800s' },
    { text: '1h', value: '+3600s' },
    { text: '3h', value: '+7200s' },
    { text: '6h', value: '+21600s' },
    { text: '1d', value: '+86400s' },
    { text: '3d', value: '+259200s' },
    { text: '1w', value: '+604800s' },
];
var stackdriverUnitMappings = {
    bit: 'bits',
    By: 'bytes',
    s: 's',
    min: 'm',
    h: 'h',
    d: 'd',
    us: 'µs',
    ms: 'ms',
    ns: 'ns',
    percent: 'percent',
    MiBy: 'mbytes',
    'By/s': 'Bps',
    GBy: 'decgbytes',
};


/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/filter_segments.ts":
/*!**********************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/filter_segments.ts ***!
  \**********************************************************************/
/*! exports provided: DefaultRemoveFilterValue, DefaultFilterValue, FilterSegments */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultRemoveFilterValue", function() { return DefaultRemoveFilterValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultFilterValue", function() { return DefaultFilterValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FilterSegments", function() { return FilterSegments; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

var DefaultRemoveFilterValue = '-- remove filter --';
var DefaultFilterValue = 'select value';
var FilterSegments = /** @class */ (function () {
    function FilterSegments(uiSegmentSrv, filters, getFilterKeysFunc, getFilterValuesFunc) {
        this.uiSegmentSrv = uiSegmentSrv;
        this.filters = filters;
        this.getFilterKeysFunc = getFilterKeysFunc;
        this.getFilterValuesFunc = getFilterValuesFunc;
    }
    FilterSegments.prototype.buildSegmentModel = function () {
        var _this = this;
        this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: DefaultRemoveFilterValue });
        this.filterSegments = [];
        this.filters.forEach(function (f, index) {
            switch (index % 4) {
                case 0:
                    _this.filterSegments.push(_this.uiSegmentSrv.newKey(f));
                    break;
                case 1:
                    _this.filterSegments.push(_this.uiSegmentSrv.newOperator(f));
                    break;
                case 2:
                    _this.filterSegments.push(_this.uiSegmentSrv.newKeyValue(f));
                    break;
                case 3:
                    _this.filterSegments.push(_this.uiSegmentSrv.newCondition(f));
                    break;
            }
        });
        this.ensurePlusButton(this.filterSegments);
    };
    FilterSegments.prototype.getFilters = function (segment, index, hasNoFilterKeys) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var filterValues;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                if (segment.type === 'condition') {
                    return [2 /*return*/, [this.uiSegmentSrv.newSegment('AND')]];
                }
                if (segment.type === 'operator') {
                    return [2 /*return*/, this.uiSegmentSrv.newOperators(['=', '!=', '=~', '!=~'])];
                }
                if (segment.type === 'key' || segment.type === 'plus-button') {
                    if (hasNoFilterKeys && segment.value && segment.value !== DefaultRemoveFilterValue) {
                        this.removeSegment.value = DefaultRemoveFilterValue;
                        return [2 /*return*/, Promise.resolve([this.removeSegment])];
                    }
                    else {
                        return [2 /*return*/, this.getFilterKeysFunc(segment, DefaultRemoveFilterValue)];
                    }
                }
                if (segment.type === 'value') {
                    filterValues = this.getFilterValuesFunc(index);
                    if (filterValues.length > 0) {
                        return [2 /*return*/, this.getValuesForFilterKey(filterValues)];
                    }
                }
                return [2 /*return*/, []];
            });
        });
    };
    FilterSegments.prototype.getValuesForFilterKey = function (labels) {
        var _this = this;
        var filterValues = labels.map(function (l) {
            return _this.uiSegmentSrv.newSegment({
                value: "" + l,
                expandable: false,
            });
        });
        return filterValues;
    };
    FilterSegments.prototype.addNewFilterSegments = function (segment, index) {
        if (index > 2) {
            this.filterSegments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
        }
        segment.type = 'key';
        this.filterSegments.push(this.uiSegmentSrv.newOperator('='));
        this.filterSegments.push(this.uiSegmentSrv.newFake(DefaultFilterValue, 'value', 'query-segment-value'));
    };
    FilterSegments.prototype.removeFilterSegment = function (index) {
        this.filterSegments.splice(index, 3);
        // remove trailing condition
        if (index > 2 && this.filterSegments[index - 1].type === 'condition') {
            this.filterSegments.splice(index - 1, 1);
        }
        // remove condition if it is first segment
        if (index === 0 && this.filterSegments.length > 0 && this.filterSegments[0].type === 'condition') {
            this.filterSegments.splice(0, 1);
        }
    };
    FilterSegments.prototype.ensurePlusButton = function (segments) {
        var count = segments.length;
        var lastSegment = segments[Math.max(count - 1, 0)];
        if (!lastSegment || lastSegment.type !== 'plus-button') {
            segments.push(this.uiSegmentSrv.newPlusButton());
        }
    };
    FilterSegments.prototype.filterSegmentUpdated = function (segment, index) {
        if (segment.type === 'plus-button') {
            this.addNewFilterSegments(segment, index);
        }
        else if (segment.type === 'key' && segment.value === DefaultRemoveFilterValue) {
            this.removeFilterSegment(index);
            this.ensurePlusButton(this.filterSegments);
        }
        else if (segment.type === 'value' && segment.value !== DefaultFilterValue) {
            this.ensurePlusButton(this.filterSegments);
        }
        return this.filterSegments.filter(function (s) { return s.type !== 'plus-button'; }).map(function (seg) { return seg.value; });
    };
    return FilterSegments;
}());



/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/functions.ts":
/*!****************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/functions.ts ***!
  \****************************************************************/
/*! exports provided: extractServicesFromMetricDescriptors, getMetricTypesByService, getMetricTypes, getAlignmentOptionsByMetric, getAggregationOptionsByMetric, getLabelKeys, getAlignmentPickerData */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "extractServicesFromMetricDescriptors", function() { return extractServicesFromMetricDescriptors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMetricTypesByService", function() { return getMetricTypesByService; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMetricTypes", function() { return getMetricTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAlignmentOptionsByMetric", function() { return getAlignmentOptionsByMetric; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAggregationOptionsByMetric", function() { return getAggregationOptionsByMetric; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLabelKeys", function() { return getLabelKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAlignmentPickerData", function() { return getAlignmentPickerData; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash_uniqBy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash/uniqBy */ "./node_modules/lodash/uniqBy.js");
/* harmony import */ var lodash_uniqBy__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_uniqBy__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./public/app/plugins/datasource/stackdriver/constants.ts");
var _this = undefined;



var extractServicesFromMetricDescriptors = function (metricDescriptors) { return lodash_uniqBy__WEBPACK_IMPORTED_MODULE_1___default()(metricDescriptors, 'service'); };
var getMetricTypesByService = function (metricDescriptors, service) {
    return metricDescriptors.filter(function (m) { return m.service === service; });
};
var getMetricTypes = function (metricDescriptors, metricType, interpolatedMetricType, selectedService) {
    var metricTypes = getMetricTypesByService(metricDescriptors, selectedService).map(function (m) { return ({
        value: m.type,
        name: m.displayName,
    }); });
    var metricTypeExistInArray = metricTypes.some(function (m) { return m.value === interpolatedMetricType; });
    var selectedMetricType = metricTypeExistInArray ? metricType : metricTypes[0].value;
    return {
        metricTypes: metricTypes,
        selectedMetricType: selectedMetricType,
    };
};
var getAlignmentOptionsByMetric = function (metricValueType, metricKind) {
    return !metricValueType
        ? []
        : _constants__WEBPACK_IMPORTED_MODULE_2__["alignOptions"].filter(function (i) {
            return i.valueTypes.indexOf(metricValueType) !== -1 && i.metricKinds.indexOf(metricKind) !== -1;
        });
};
var getAggregationOptionsByMetric = function (valueType, metricKind) {
    return !metricKind
        ? []
        : _constants__WEBPACK_IMPORTED_MODULE_2__["aggOptions"].filter(function (i) {
            return i.valueTypes.indexOf(valueType) !== -1 && i.metricKinds.indexOf(metricKind) !== -1;
        });
};
var getLabelKeys = function (datasource, selectedMetricType) { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () {
    var refId, response, labelKeys;
    return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
        switch (_a.label) {
            case 0:
                refId = 'handleLabelKeysQuery';
                return [4 /*yield*/, datasource.getLabels(selectedMetricType, refId)];
            case 1:
                response = _a.sent();
                labelKeys = response.meta
                    ? tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](Object.keys(response.meta.resourceLabels).map(function (l) { return "resource.label." + l; }), Object.keys(response.meta.metricLabels).map(function (l) { return "metric.label." + l; })) : [];
                return [2 /*return*/, labelKeys];
        }
    });
}); };
var getAlignmentPickerData = function (_a, templateSrv) {
    var valueType = _a.valueType, metricKind = _a.metricKind, perSeriesAligner = _a.perSeriesAligner;
    var options = getAlignmentOptionsByMetric(valueType, metricKind).map(function (option) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, option, { label: option.text })); });
    var alignOptions = [
        {
            label: 'Alignment options',
            expanded: true,
            options: options,
        },
    ];
    if (!options.some(function (o) { return o.value === templateSrv.replace(perSeriesAligner); })) {
        perSeriesAligner = options.length > 0 ? options[0].value : '';
    }
    return { alignOptions: alignOptions, perSeriesAligner: perSeriesAligner };
};


/***/ }),

/***/ "./public/app/plugins/datasource/stackdriver/query_filter_ctrl.ts":
/*!************************************************************************!*\
  !*** ./public/app/plugins/datasource/stackdriver/query_filter_ctrl.ts ***!
  \************************************************************************/
/*! exports provided: StackdriverFilterCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StackdriverFilterCtrl", function() { return StackdriverFilterCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _filter_segments__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./filter_segments */ "./public/app/plugins/datasource/stackdriver/filter_segments.ts");



var StackdriverFilterCtrl = /** @class */ (function () {
    /** @ngInject */
    function StackdriverFilterCtrl($scope, uiSegmentSrv, templateSrv) {
        this.$scope = $scope;
        this.uiSegmentSrv = uiSegmentSrv;
        this.templateSrv = templateSrv;
        this.defaultRemoveGroupByValue = '-- remove group by --';
        this.resourceTypeValue = 'resource.type';
        this.$scope.ctrl = this;
        this.initSegments(this.hideGroupBys);
    }
    StackdriverFilterCtrl.prototype.initSegments = function (hideGroupBys) {
        var _this = this;
        if (!hideGroupBys) {
            this.groupBySegments = this.groupBys.map(function (groupBy) {
                return _this.uiSegmentSrv.getSegmentForValue(groupBy);
            });
            this.ensurePlusButton(this.groupBySegments);
        }
        this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });
        this.filterSegments = new _filter_segments__WEBPACK_IMPORTED_MODULE_2__["FilterSegments"](this.uiSegmentSrv, this.filters, this.getFilterKeys.bind(this), this.getFilterValues.bind(this));
        this.filterSegments.buildSegmentModel();
    };
    StackdriverFilterCtrl.prototype.createLabelKeyElements = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var elements;
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.loading];
                    case 1:
                        _a.sent();
                        elements = Object.keys(this.labelData.metricLabels || {}).map(function (l) {
                            return _this.uiSegmentSrv.newSegment({
                                value: "metric.label." + l,
                                expandable: false,
                            });
                        });
                        elements = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](elements, Object.keys(this.labelData.resourceLabels || {}).map(function (l) {
                            return _this.uiSegmentSrv.newSegment({
                                value: "resource.label." + l,
                                expandable: false,
                            });
                        }));
                        if (this.labelData.resourceTypes && this.labelData.resourceTypes.length > 0) {
                            elements = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](elements, [
                                this.uiSegmentSrv.newSegment({
                                    value: this.resourceTypeValue,
                                    expandable: false,
                                }),
                            ]);
                        }
                        return [2 /*return*/, elements];
                }
            });
        });
    };
    StackdriverFilterCtrl.prototype.getFilterKeys = function (segment, removeText) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var elements, noValueOrPlusButton;
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.createLabelKeyElements()];
                    case 1:
                        elements = _a.sent();
                        if (this.filters.indexOf(this.resourceTypeValue) !== -1) {
                            elements = elements.filter(function (e) { return e.value !== _this.resourceTypeValue; });
                        }
                        noValueOrPlusButton = !segment || segment.type === 'plus-button';
                        if (noValueOrPlusButton && elements.length === 0) {
                            return [2 /*return*/, []];
                        }
                        return [2 /*return*/, segment.type === 'plus-button'
                                ? elements
                                : tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](elements, [
                                    this.uiSegmentSrv.newSegment({ fake: true, value: removeText || this.defaultRemoveGroupByValue }),
                                ])];
                }
            });
        });
    };
    StackdriverFilterCtrl.prototype.getGroupBys = function (segment) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var elements, noValueOrPlusButton;
            var _this = this;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.createLabelKeyElements()];
                    case 1:
                        elements = _a.sent();
                        elements = elements.filter(function (e) { return _this.groupBys.indexOf(e.value) === -1; });
                        noValueOrPlusButton = !segment || segment.type === 'plus-button';
                        if (noValueOrPlusButton && elements.length === 0) {
                            return [2 /*return*/, []];
                        }
                        this.removeSegment.value = this.defaultRemoveGroupByValue;
                        return [2 /*return*/, segment.type === 'plus-button' ? elements : tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](elements, [this.removeSegment])];
                }
            });
        });
    };
    StackdriverFilterCtrl.prototype.groupByChanged = function (segment, index) {
        if (segment.value === this.removeSegment.value) {
            this.groupBySegments.splice(index, 1);
        }
        else {
            segment.type = 'value';
        }
        var reducer = function (memo, seg) {
            if (!seg.fake) {
                memo.push(seg.value);
            }
            return memo;
        };
        var groupBys = this.groupBySegments.reduce(reducer, []);
        this.groupBysChanged({ groupBys: groupBys });
        this.ensurePlusButton(this.groupBySegments);
    };
    StackdriverFilterCtrl.prototype.getFilters = function (segment, index) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var hasNoFilterKeys;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.loading];
                    case 1:
                        _a.sent();
                        hasNoFilterKeys = this.labelData.metricLabels && Object.keys(this.labelData.metricLabels).length === 0;
                        return [2 /*return*/, this.filterSegments.getFilters(segment, index, hasNoFilterKeys)];
                }
            });
        });
    };
    StackdriverFilterCtrl.prototype.getFilterValues = function (index) {
        var filterKey = this.templateSrv.replace(this.filterSegments.filterSegments[index - 2].value);
        if (!filterKey || !this.labelData.metricLabels || Object.keys(this.labelData.metricLabels).length === 0) {
            return [];
        }
        var shortKey = filterKey.substring(filterKey.indexOf('.label.') + 7);
        if (filterKey.startsWith('metric.label.') && this.labelData.metricLabels.hasOwnProperty(shortKey)) {
            return this.labelData.metricLabels[shortKey];
        }
        if (filterKey.startsWith('resource.label.') && this.labelData.resourceLabels.hasOwnProperty(shortKey)) {
            return this.labelData.resourceLabels[shortKey];
        }
        if (filterKey === this.resourceTypeValue) {
            return this.labelData.resourceTypes;
        }
        return [];
    };
    StackdriverFilterCtrl.prototype.filterSegmentUpdated = function (segment, index) {
        var filters = this.filterSegments.filterSegmentUpdated(segment, index);
        if (!filters.some(function (f) { return f === _filter_segments__WEBPACK_IMPORTED_MODULE_2__["DefaultFilterValue"]; })) {
            this.filtersChanged({ filters: filters });
        }
    };
    StackdriverFilterCtrl.prototype.ensurePlusButton = function (segments) {
        var count = segments.length;
        var lastSegment = segments[Math.max(count - 1, 0)];
        if (!lastSegment || lastSegment.type !== 'plus-button') {
            segments.push(this.uiSegmentSrv.newPlusButton());
        }
    };
    return StackdriverFilterCtrl;
}());

/** @ngInject */
function stackdriverFilter() {
    return {
        templateUrl: 'public/app/plugins/datasource/stackdriver/partials/query.filter.html',
        controller: StackdriverFilterCtrl,
        controllerAs: 'ctrl',
        bindToController: true,
        restrict: 'E',
        scope: {
            labelData: '<',
            loading: '<',
            groupBys: '<',
            filters: '<',
            filtersChanged: '&',
            groupBysChanged: '&',
            hideGroupBys: '<',
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].directive('stackdriverFilter', stackdriverFilter);


/***/ }),

/***/ "./public/app/plugins/panel/alertlist/module.ts":
/*!******************************************************!*\
  !*** ./public/app/plugins/panel/alertlist/module.ts ***!
  \******************************************************/
/*! exports provided: AlertListPanel, PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertListPanel", function() { return AlertListPanel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return AlertListPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _features_alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../features/alerting/state/alertDef */ "./public/app/features/alerting/state/alertDef.ts");
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");






var AlertListPanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AlertListPanel, _super);
    /** @ngInject */
    function AlertListPanel($scope, $injector, backendSrv) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.backendSrv = backendSrv;
        _this.showOptions = [{ text: 'Current state', value: 'current' }, { text: 'Recent state changes', value: 'changes' }];
        _this.sortOrderOptions = [
            { text: 'Alphabetical (asc)', value: 1 },
            { text: 'Alphabetical (desc)', value: 2 },
            { text: 'Importance', value: 3 },
        ];
        _this.stateFilter = {};
        _this.currentAlerts = [];
        _this.alertHistory = [];
        // Set and populate defaults
        _this.panelDefaults = {
            show: 'current',
            limit: 10,
            stateFilter: [],
            onlyAlertsOnDashboard: false,
            sortOrder: 1,
            dashboardFilter: '',
            nameFilter: '',
            folderId: null,
        };
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.panel, _this.panelDefaults);
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.events.on('refresh', _this.onRefresh.bind(_this));
        _this.templateSrv = _this.$injector.get('templateSrv');
        for (var key in _this.panel.stateFilter) {
            _this.stateFilter[_this.panel.stateFilter[key]] = true;
        }
        return _this;
    }
    AlertListPanel.prototype.sortResult = function (alerts) {
        if (this.panel.sortOrder === 3) {
            return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(alerts, function (a) {
                // @ts-ignore
                return _features_alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_2__["default"].alertStateSortScore[a.state];
            });
        }
        var result = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(alerts, function (a) {
            return a.name.toLowerCase();
        });
        if (this.panel.sortOrder === 2) {
            result.reverse();
        }
        return result;
    };
    AlertListPanel.prototype.updateStateFilter = function () {
        var result = [];
        for (var key in this.stateFilter) {
            if (this.stateFilter[key]) {
                result.push(key);
            }
        }
        this.panel.stateFilter = result;
        this.onRefresh();
    };
    AlertListPanel.prototype.onRefresh = function () {
        var _this = this;
        var getAlertsPromise;
        if (this.panel.show === 'current') {
            getAlertsPromise = this.getCurrentAlertState();
        }
        if (this.panel.show === 'changes') {
            getAlertsPromise = this.getStateChanges();
        }
        getAlertsPromise.then(function () {
            _this.renderingCompleted();
        });
    };
    AlertListPanel.prototype.onFolderChange = function (folder) {
        this.panel.folderId = folder.id;
        this.refresh();
    };
    AlertListPanel.prototype.getStateChanges = function () {
        var _this = this;
        var params = {
            limit: this.panel.limit,
            type: 'alert',
            newState: this.panel.stateFilter,
        };
        if (this.panel.onlyAlertsOnDashboard) {
            params.dashboardId = this.dashboard.id;
        }
        params.from = _grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateMath"].parse(this.dashboard.time.from).unix() * 1000;
        params.to = _grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateMath"].parse(this.dashboard.time.to).unix() * 1000;
        return this.backendSrv.get("/api/annotations", params).then(function (res) {
            _this.alertHistory = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(res, function (al) {
                al.time = _this.dashboard.formatDate(al.time, 'MMM D, YYYY HH:mm:ss');
                al.stateModel = _features_alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_2__["default"].getStateDisplayModel(al.newState);
                al.info = _features_alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_2__["default"].getAlertAnnotationInfo(al);
                return al;
            });
            _this.noAlertsMessage = _this.alertHistory.length === 0 ? 'No alerts in current time range' : '';
            return _this.alertHistory;
        });
    };
    AlertListPanel.prototype.getCurrentAlertState = function () {
        var _this = this;
        var params = {
            state: this.panel.stateFilter,
        };
        if (this.panel.nameFilter) {
            params.query = this.templateSrv.replace(this.panel.nameFilter, this.panel.scopedVars);
        }
        if (this.panel.folderId >= 0) {
            params.folderId = this.panel.folderId;
        }
        if (this.panel.dashboardFilter) {
            params.dashboardQuery = this.panel.dashboardFilter;
        }
        if (this.panel.onlyAlertsOnDashboard) {
            params.dashboardId = this.dashboard.id;
        }
        if (this.panel.dashboardTags) {
            params.dashboardTag = this.panel.dashboardTags;
        }
        return this.backendSrv.get("/api/alerts", params).then(function (res) {
            _this.currentAlerts = _this.sortResult(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(res, function (al) {
                al.stateModel = _features_alerting_state_alertDef__WEBPACK_IMPORTED_MODULE_2__["default"].getStateDisplayModel(al.state);
                al.newStateDateAgo = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(al.newStateDate)
                    .locale('en')
                    .fromNow(true);
                return al;
            }));
            if (_this.currentAlerts.length > _this.panel.limit) {
                _this.currentAlerts = _this.currentAlerts.slice(0, _this.panel.limit);
            }
            _this.noAlertsMessage = _this.currentAlerts.length === 0 ? 'No alerts' : '';
            return _this.currentAlerts;
        });
    };
    AlertListPanel.prototype.onInitEditMode = function () {
        this.addEditorTab('Options', 'public/app/plugins/panel/alertlist/editor.html');
    };
    AlertListPanel.templateUrl = 'module.html';
    AlertListPanel.scrollable = true;
    return AlertListPanel;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_3__["PanelCtrl"]));



/***/ }),

/***/ "./public/app/plugins/panel/annolist/AnnoListEditor.tsx":
/*!**************************************************************!*\
  !*** ./public/app/plugins/panel/annolist/AnnoListEditor.tsx ***!
  \**************************************************************/
/*! exports provided: AnnoListEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnnoListEditor", function() { return AnnoListEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_components_TagFilter_TagBadge__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/components/TagFilter/TagBadge */ "./public/app/core/components/TagFilter/TagBadge.tsx");

// Libraries

// Components



var AnnoListEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnnoListEditor, _super);
    function AnnoListEditor(props) {
        var _this = _super.call(this, props) || this;
        // Display
        //-----------
        _this.onToggleShowUser = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { showUser: !_this.props.options.showUser }));
        };
        _this.onToggleShowTime = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { showTime: !_this.props.options.showTime }));
        };
        _this.onToggleShowTags = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { showTags: !_this.props.options.showTags }));
        };
        // Navigate
        //-----------
        _this.onNavigateBeforeChange = function (event) {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { navigateBefore: event.target.value }));
        };
        _this.onNavigateAfterChange = function (event) {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { navigateAfter: event.target.value }));
        };
        _this.onToggleNavigateToPanel = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { navigateToPanel: !_this.props.options.navigateToPanel }));
        };
        // Search
        //-----------
        _this.onLimitChange = function (event) {
            var v = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toIntegerOrUndefined"])(event.target.value);
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { limit: v }));
        };
        _this.onToggleOnlyFromThisDashboard = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { onlyFromThisDashboard: !_this.props.options.onlyFromThisDashboard }));
        };
        _this.onToggleOnlyInTimeRange = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { onlyInTimeRange: !_this.props.options.onlyInTimeRange }));
        };
        // Tags
        //-----------
        _this.onTagTextChange = function (event) {
            _this.setState({ tag: event.target.value });
        };
        _this.onTagClick = function (e, tag) {
            e.stopPropagation();
            var tags = _this.props.options.tags.filter(function (item) { return item !== tag; });
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { tags: tags }));
        };
        _this.renderTags = function (tags) {
            if (!tags || !tags.length) {
                return null;
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, tags.map(function (tag) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: tag, onClick: function (e) { return _this.onTagClick(e, tag); }, className: "pointer" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_TagFilter_TagBadge__WEBPACK_IMPORTED_MODULE_4__["TagBadge"], { label: tag, removeIcon: true, count: 0 })));
            })));
        };
        _this.state = {
            tag: '',
        };
        return _this;
    }
    AnnoListEditor.prototype.render = function () {
        var _this = this;
        var options = this.props.options;
        var labelWidth = 8;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGrid"], null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Display" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Show User", labelClass: "width-" + labelWidth, checked: options.showUser, onChange: this.onToggleShowUser }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Show Time", labelClass: "width-" + labelWidth, checked: options.showTime, onChange: this.onToggleShowTime }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Show Tags", labelClass: "width-" + labelWidth, checked: options.showTags, onChange: this.onToggleShowTags })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Navigate" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Before", labelWidth: labelWidth, onChange: this.onNavigateBeforeChange, value: options.navigateBefore }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "After", labelWidth: labelWidth, onChange: this.onNavigateAfterChange, value: options.navigateAfter }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "To Panel", labelClass: "width-" + labelWidth, checked: options.navigateToPanel, onChange: this.onToggleNavigateToPanel })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Search" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Only This Dashboard", labelClass: "width-12", checked: options.onlyFromThisDashboard, onChange: this.onToggleOnlyFromThisDashboard }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Within Time Range", labelClass: "width-12", checked: options.onlyInTimeRange, onChange: this.onToggleOnlyInTimeRange }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "form-field" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: 6 }, "Tags"),
                    this.renderTags(options.tags),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", { type: "text", className: "gf-form-input width-" + 8, value: this.state.tag, onChange: this.onTagTextChange, onKeyPress: function (ev) {
                            if (_this.state.tag && ev.key === 'Enter') {
                                var tags = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](options.tags, [_this.state.tag]);
                                _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { tags: tags }));
                                _this.setState({ tag: '' });
                                ev.preventDefault();
                            }
                        } })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Limit", labelWidth: 6, onChange: this.onLimitChange, value: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["toNumberString"])(options.limit), type: "number" }))));
    };
    return AnnoListEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/annolist/AnnoListPanel.tsx":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/annolist/AnnoListPanel.tsx ***!
  \*************************************************************/
/*! exports provided: AnnoListPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnnoListPanel", function() { return AnnoListPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");
/* harmony import */ var _grafana_ui_src_components_List_AbstractList__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/ui/src/components/List/AbstractList */ "./packages/grafana-ui/src/components/List/AbstractList.tsx");
/* harmony import */ var app_core_components_TagFilter_TagBadge__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/components/TagFilter/TagBadge */ "./public/app/core/components/TagFilter/TagBadge.tsx");
/* harmony import */ var app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/features/dashboard/services/DashboardSrv */ "./public/app/features/dashboard/services/DashboardSrv.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var app_store_store__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! app/store/store */ "./public/app/store/store.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");

// Libraries











var AnnoListPanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnnoListPanel, _super);
    function AnnoListPanel(props) {
        var _this = _super.call(this, props) || this;
        _this.onAnnoClick = function (e, anno) {
            e.stopPropagation();
            var options = _this.props.options;
            var dashboardSrv = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__["getDashboardSrv"])();
            var current = dashboardSrv.getCurrent();
            var params = {
                from: _this._timeOffset(anno.time, options.navigateBefore, true),
                to: _this._timeOffset(anno.time, options.navigateAfter, false),
            };
            if (options.navigateToPanel) {
                params.panelId = anno.panelId;
                params.fullscreen = true;
            }
            if (current.id === anno.dashboardId) {
                app_store_store__WEBPACK_IMPORTED_MODULE_10__["store"].dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_9__["updateLocation"])({
                    query: params,
                    partial: true,
                }));
                return;
            }
            Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__["getBackendSrv"])()
                .get('/api/search', { dashboardIds: anno.dashboardId })
                .then(function (res) {
                if (res && res.length && res[0].id === anno.dashboardId) {
                    var dash = res[0];
                    app_store_store__WEBPACK_IMPORTED_MODULE_10__["store"].dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_9__["updateLocation"])({
                        query: params,
                        path: dash.url,
                    }));
                    return;
                }
                app_core_app_events__WEBPACK_IMPORTED_MODULE_8__["default"].emit('alert-warning', ['Unknown Dashboard: ' + anno.dashboardId]);
            });
        };
        _this.onTagClick = function (e, tag, remove) {
            e.stopPropagation();
            var queryTags = remove ? _this.state.queryTags.filter(function (item) { return item !== tag; }) : tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](_this.state.queryTags, [tag]);
            _this.setState({ queryTags: queryTags });
        };
        _this.onUserClick = function (e, anno) {
            e.stopPropagation();
            _this.setState({
                queryUser: {
                    id: anno.userId,
                    login: anno.login,
                    email: anno.email,
                },
            });
        };
        _this.onClearUser = function () {
            _this.setState({
                queryUser: undefined,
            });
        };
        _this.renderTags = function (tags, remove) {
            if (!tags || !tags.length) {
                return null;
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, tags.map(function (tag) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { key: tag, onClick: function (e) { return _this.onTagClick(e, tag, remove); }, className: "pointer" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(app_core_components_TagFilter_TagBadge__WEBPACK_IMPORTED_MODULE_6__["TagBadge"], { label: tag, removeIcon: remove, count: 0 })));
            })));
        };
        _this.renderItem = function (anno, index) {
            var options = _this.props.options;
            var showUser = options.showUser, showTags = options.showTags, showTime = options.showTime;
            var dashboard = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__["getDashboardSrv"])().getCurrent();
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "dashlist-item" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "dashlist-link pointer", onClick: function (e) {
                        _this.onAnnoClick(e, anno);
                    } },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_11__["cx"])([
                            'dashlist-title',
                            Object(emotion__WEBPACK_IMPORTED_MODULE_11__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                margin-right: 8px;\n              "], ["\n                margin-right: 8px;\n              "]))),
                        ]) }, anno.text),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "pluginlist-message" },
                        anno.login && showUser && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "graph-annotation" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["Tooltip"], { content: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null,
                                    "Created by:",
                                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("br", null),
                                    " ",
                                    anno.email), theme: "info", placement: "top" },
                                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { onClick: function (e) { return _this.onUserClick(e, anno); }, className: "graph-annotation__user" },
                                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", { src: anno.avatarUrl }))))),
                        showTags && _this.renderTags(anno.tags, false)),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "pluginlist-version" }, showTime && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, dashboard.formatDate(anno.time))))));
        };
        _this.state = {
            annotations: [],
            timeInfo: '',
            loaded: false,
            queryTags: [],
        };
        return _this;
    }
    AnnoListPanel.prototype.componentDidMount = function () {
        this.doSearch();
    };
    AnnoListPanel.prototype.componentDidUpdate = function (prevProps, prevState) {
        var _a = this.props, options = _a.options, timeRange = _a.timeRange;
        var needsQuery = options !== prevProps.options ||
            this.state.queryTags !== prevState.queryTags ||
            this.state.queryUser !== prevState.queryUser ||
            timeRange !== prevProps.timeRange;
        if (needsQuery) {
            this.doSearch();
        }
    };
    AnnoListPanel.prototype.doSearch = function () {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](this, void 0, void 0, function () {
            var options, _a, queryUser, queryTags, params, timeInfo, timeRange, annotations;
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_b) {
                switch (_b.label) {
                    case 0:
                        options = this.props.options;
                        _a = this.state, queryUser = _a.queryUser, queryTags = _a.queryTags;
                        params = {
                            tags: options.tags,
                            limit: options.limit,
                            type: 'annotation',
                        };
                        if (options.onlyFromThisDashboard) {
                            params.dashboardId = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_7__["getDashboardSrv"])().getCurrent().id;
                        }
                        timeInfo = '';
                        if (options.onlyInTimeRange) {
                            timeRange = this.props.timeRange;
                            params.from = timeRange.from.valueOf();
                            params.to = timeRange.to.valueOf();
                        }
                        else {
                            timeInfo = 'All Time';
                        }
                        if (queryUser) {
                            params.userId = queryUser.id;
                        }
                        if (options.tags && options.tags.length) {
                            params.tags = options.tags;
                        }
                        if (queryTags.length) {
                            params.tags = params.tags ? tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](params.tags, queryTags) : queryTags;
                        }
                        return [4 /*yield*/, Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_4__["getBackendSrv"])().get('/api/annotations', params)];
                    case 1:
                        annotations = _b.sent();
                        this.setState({
                            annotations: annotations,
                            timeInfo: timeInfo,
                            loaded: true,
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    AnnoListPanel.prototype._timeOffset = function (time, offset, subtract) {
        if (subtract === void 0) { subtract = false; }
        var incr = 5;
        var unit = 'm';
        var parts = /^(\d+)(\w)/.exec(offset);
        if (parts && parts.length === 3) {
            incr = parseInt(parts[1], 10);
            unit = parts[2];
        }
        var t = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(time);
        if (subtract) {
            incr *= -1;
        }
        return t.add(incr, unit).valueOf();
    };
    AnnoListPanel.prototype.render = function () {
        var height = this.props.height;
        var _a = this.state, loaded = _a.loaded, annotations = _a.annotations, queryUser = _a.queryUser, queryTags = _a.queryTags;
        if (!loaded) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, "loading...");
        }
        // Previously we showed inidication that it covered all time
        // { timeInfo && (
        //   <span className="panel-time-info">
        //     <i className="fa fa-clock-o" /> {timeInfo}
        //   </span>
        // )}
        var hasFilter = queryUser || queryTags.length > 0;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { style: { height: height, overflow: 'scroll' } },
            hasFilter && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("b", null, "Filter: \u00A0 "),
                queryUser && (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { onClick: this.onClearUser, className: "pointer" }, queryUser.email)),
                queryTags.length > 0 && this.renderTags(queryTags, true))),
            annotations.length < 1 && react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "panel-alert-list__no-alerts" }, "No Annotations Found"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui_src_components_List_AbstractList__WEBPACK_IMPORTED_MODULE_5__["AbstractList"], { items: annotations, renderItem: this.renderItem, getItemKey: function (item) {
                    return item.id + '';
                }, className: "dashlist" })));
    };
    return AnnoListPanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var templateObject_1;


/***/ }),

/***/ "./public/app/plugins/panel/annolist/module.ts":
/*!*****************************************************!*\
  !*** ./public/app/plugins/panel/annolist/module.ts ***!
  \*****************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _AnnoListPanel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AnnoListPanel */ "./public/app/plugins/panel/annolist/AnnoListPanel.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/annolist/types.ts");
/* harmony import */ var _AnnoListEditor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AnnoListEditor */ "./public/app/plugins/panel/annolist/AnnoListEditor.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["PanelPlugin"](_AnnoListPanel__WEBPACK_IMPORTED_MODULE_0__["AnnoListPanel"])
    .setDefaults(_types__WEBPACK_IMPORTED_MODULE_1__["defaults"])
    .setEditor(_AnnoListEditor__WEBPACK_IMPORTED_MODULE_2__["AnnoListEditor"])
    // TODO, we should support this directly in the plugin infrastructure
    .setPanelChangeHandler(function (options, prevPluginId, prevOptions) {
    if (prevPluginId === 'ryantxu-annolist-panel') {
        return prevOptions;
    }
    return options;
});


/***/ }),

/***/ "./public/app/plugins/panel/annolist/types.ts":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/annolist/types.ts ***!
  \****************************************************/
/*! exports provided: defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
var defaults = {
    limit: 10,
    tags: [],
    onlyFromThisDashboard: false,
    onlyInTimeRange: false,
    showTags: true,
    showUser: true,
    showTime: true,
    navigateBefore: '10m',
    navigateAfter: '10m',
    navigateToPanel: true,
};


/***/ }),

/***/ "./public/app/plugins/panel/bargauge/BarGaugeMigrations.ts":
/*!*****************************************************************!*\
  !*** ./public/app/plugins/panel/bargauge/BarGaugeMigrations.ts ***!
  \*****************************************************************/
/*! exports provided: barGaugePanelMigrationHandler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "barGaugePanelMigrationHandler", function() { return barGaugePanelMigrationHandler; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

var barGaugePanelMigrationHandler = function (panel) {
    return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatMigrationHandler"])(panel);
};


/***/ }),

/***/ "./public/app/plugins/panel/bargauge/BarGaugePanel.tsx":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/bargauge/BarGaugePanel.tsx ***!
  \*************************************************************/
/*! exports provided: BarGaugePanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BarGaugePanel", function() { return BarGaugePanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/panel/panellinks/linkSuppliers */ "./public/app/features/panel/panellinks/linkSuppliers.ts");

// Libraries

// Services & Utils

// Components


var BarGaugePanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BarGaugePanel, _super);
    function BarGaugePanel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.renderValue = function (value, width, height) {
            var options = _this.props.options;
            var field = value.field, display = value.display;
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DataLinksContextMenu"], { links: Object(app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_4__["getFieldLinksSupplier"])(value) }, function (_a) {
                var openMenu = _a.openMenu, targetClassName = _a.targetClassName;
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["BarGauge"], { value: display, width: width, height: height, orientation: options.orientation, thresholds: field.thresholds, theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme, itemSpacing: _this.getItemSpacing(), displayMode: options.displayMode, minValue: field.min, maxValue: field.max, onClick: openMenu, className: targetClassName }));
            }));
        };
        _this.getValues = function () {
            var _a = _this.props, data = _a.data, options = _a.options, replaceVariables = _a.replaceVariables;
            return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getFieldDisplayValues"])(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { replaceVariables: replaceVariables, theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme, data: data.series }));
        };
        return _this;
    }
    BarGaugePanel.prototype.getItemSpacing = function () {
        if (this.props.options.displayMode === 'lcd') {
            return 2;
        }
        return 10;
    };
    BarGaugePanel.prototype.render = function () {
        var _a = this.props, height = _a.height, width = _a.width, options = _a.options, data = _a.data, renderCounter = _a.renderCounter;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["VizRepeater"], { source: data, getValues: this.getValues, renderValue: this.renderValue, renderCounter: renderCounter, width: width, height: height, itemSpacing: this.getItemSpacing(), orientation: options.orientation }));
    };
    return BarGaugePanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/bargauge/BarGaugePanelEditor.tsx":
/*!*******************************************************************!*\
  !*** ./public/app/plugins/panel/bargauge/BarGaugePanelEditor.tsx ***!
  \*******************************************************************/
/*! exports provided: BarGaugePanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BarGaugePanelEditor", function() { return BarGaugePanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/bargauge/types.ts");
/* harmony import */ var app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/panel/panellinks/link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");

// Libraries




var BarGaugePanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BarGaugePanelEditor, _super);
    function BarGaugePanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onThresholdsChanged = function (thresholds) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { thresholds: thresholds }));
        };
        _this.onValueMappingsChanged = function (mappings) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { mappings: mappings }));
        };
        _this.onDisplayOptionsChanged = function (fieldOptions) {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { fieldOptions: fieldOptions }));
        };
        _this.onDefaultsChange = function (field) {
            _this.onDisplayOptionsChanged(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions, { defaults: field }));
        };
        _this.onOrientationChange = function (_a) {
            var value = _a.value;
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { orientation: value }));
        };
        _this.onDisplayModeChange = function (_a) {
            var value = _a.value;
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { displayMode: value }));
        };
        _this.onDataLinksChanged = function (links) {
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions.defaults, { links: links }));
        };
        return _this;
    }
    BarGaugePanelEditor.prototype.render = function () {
        var options = this.props.options;
        var fieldOptions = options.fieldOptions;
        var defaults = fieldOptions.defaults;
        var suggestions = fieldOptions.values
            ? Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_4__["getDataLinksVariableSuggestions"])(this.props.data.series)
            : Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_4__["getCalculationValueDataLinksVariableSuggestions"])(this.props.data.series);
        var labelWidth = 6;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGrid"], null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Display" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldDisplayEditor"], { onChange: this.onDisplayOptionsChanged, value: fieldOptions, labelWidth: labelWidth }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "form-field" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Orientation"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { width: 12, options: _types__WEBPACK_IMPORTED_MODULE_3__["orientationOptions"], defaultValue: _types__WEBPACK_IMPORTED_MODULE_3__["orientationOptions"][0], onChange: this.onOrientationChange, value: _types__WEBPACK_IMPORTED_MODULE_3__["orientationOptions"].find(function (item) { return item.value === options.orientation; }) })),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "form-field" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Mode"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { width: 12, options: _types__WEBPACK_IMPORTED_MODULE_3__["displayModes"], defaultValue: _types__WEBPACK_IMPORTED_MODULE_3__["displayModes"][0], onChange: this.onDisplayModeChange, value: _types__WEBPACK_IMPORTED_MODULE_3__["displayModes"].find(function (item) { return item.value === options.displayMode; }) }))),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Field" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldPropertiesEditor"], { showMinMax: true, onChange: this.onDefaultsChange, value: defaults })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ThresholdsEditor"], { onChange: this.onThresholdsChanged, thresholds: defaults.thresholds })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ValueMappingsEditor"], { onChange: this.onValueMappingsChanged, valueMappings: defaults.mappings }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Data links" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DataLinksEditor"], { value: defaults.links, onChange: this.onDataLinksChanged, suggestions: suggestions, maxLinks: 10 }))));
    };
    return BarGaugePanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/bargauge/module.tsx":
/*!******************************************************!*\
  !*** ./public/app/plugins/panel/bargauge/module.tsx ***!
  \******************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _BarGaugePanel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BarGaugePanel */ "./public/app/plugins/panel/bargauge/BarGaugePanel.tsx");
/* harmony import */ var _BarGaugePanelEditor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BarGaugePanelEditor */ "./public/app/plugins/panel/bargauge/BarGaugePanelEditor.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/bargauge/types.ts");
/* harmony import */ var _BarGaugeMigrations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./BarGaugeMigrations */ "./public/app/plugins/panel/bargauge/BarGaugeMigrations.ts");





var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_BarGaugePanel__WEBPACK_IMPORTED_MODULE_1__["BarGaugePanel"])
    .setDefaults(_types__WEBPACK_IMPORTED_MODULE_3__["defaults"])
    .setEditor(_BarGaugePanelEditor__WEBPACK_IMPORTED_MODULE_2__["BarGaugePanelEditor"])
    .setPanelChangeHandler(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatPanelChangedHandler"])
    .setMigrationHandler(_BarGaugeMigrations__WEBPACK_IMPORTED_MODULE_4__["barGaugePanelMigrationHandler"]);


/***/ }),

/***/ "./public/app/plugins/panel/bargauge/types.ts":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/bargauge/types.ts ***!
  \****************************************************/
/*! exports provided: displayModes, orientationOptions, defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayModes", function() { return displayModes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "orientationOptions", function() { return orientationOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _gauge_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../gauge/types */ "./public/app/plugins/panel/gauge/types.ts");


var displayModes = [
    { value: 'gradient', label: 'Gradient' },
    { value: 'lcd', label: 'Retro LCD' },
    { value: 'basic', label: 'Basic' },
];
var orientationOptions = [
    { value: _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["VizOrientation"].Horizontal, label: 'Horizontal' },
    { value: _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["VizOrientation"].Vertical, label: 'Vertical' },
];
var defaults = {
    displayMode: 'lcd',
    orientation: _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["VizOrientation"].Horizontal,
    fieldOptions: _gauge_types__WEBPACK_IMPORTED_MODULE_1__["standardGaugeFieldOptions"],
};


/***/ }),

/***/ "./public/app/plugins/panel/dashlist/module.ts":
/*!*****************************************************!*\
  !*** ./public/app/plugins/panel/dashlist/module.ts ***!
  \*****************************************************/
/*! exports provided: DashListCtrl, PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashListCtrl", function() { return DashListCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return DashListCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/services/impression_srv */ "./public/app/core/services/impression_srv.ts");




var DashListCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DashListCtrl, _super);
    /** @ngInject */
    function DashListCtrl($scope, $injector, backendSrv, dashboardSrv) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.backendSrv = backendSrv;
        _this.dashboardSrv = dashboardSrv;
        _this.panelDefaults = {
            query: '',
            limit: 10,
            tags: [],
            recent: false,
            search: false,
            starred: true,
            headings: true,
            folderId: null,
        };
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.panel, _this.panelDefaults);
        if (_this.panel.tag) {
            _this.panel.tags = [_this.panel.tag];
            delete _this.panel.tag;
        }
        _this.events.on('refresh', _this.onRefresh.bind(_this));
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.groups = [
            { list: [], show: false, header: 'Starred dashboards' },
            { list: [], show: false, header: 'Recently viewed dashboards' },
            { list: [], show: false, header: 'Search' },
        ];
        // update capability
        if (_this.panel.mode) {
            if (_this.panel.mode === 'starred') {
                _this.panel.starred = true;
                _this.panel.headings = false;
            }
            if (_this.panel.mode === 'recently viewed') {
                _this.panel.recent = true;
                _this.panel.starred = false;
                _this.panel.headings = false;
            }
            if (_this.panel.mode === 'search') {
                _this.panel.search = true;
                _this.panel.starred = false;
                _this.panel.headings = false;
            }
            delete _this.panel.mode;
        }
        return _this;
    }
    DashListCtrl.prototype.onInitEditMode = function () {
        this.modes = ['starred', 'search', 'recently viewed'];
        this.addEditorTab('Options', 'public/app/plugins/panel/dashlist/editor.html');
    };
    DashListCtrl.prototype.onRefresh = function () {
        var promises = [];
        promises.push(this.getRecentDashboards());
        promises.push(this.getStarred());
        promises.push(this.getSearch());
        return Promise.all(promises).then(this.renderingCompleted.bind(this));
    };
    DashListCtrl.prototype.getSearch = function () {
        var _this = this;
        this.groups[2].show = this.panel.search;
        if (!this.panel.search) {
            return Promise.resolve();
        }
        var params = {
            limit: this.panel.limit,
            query: this.panel.query,
            tag: this.panel.tags,
            folderIds: this.panel.folderId,
            type: 'dash-db',
        };
        return this.backendSrv.search(params).then(function (result) {
            _this.groups[2].list = result;
        });
    };
    DashListCtrl.prototype.getStarred = function () {
        var _this = this;
        this.groups[0].show = this.panel.starred;
        if (!this.panel.starred) {
            return Promise.resolve();
        }
        var params = { limit: this.panel.limit, starred: 'true' };
        return this.backendSrv.search(params).then(function (result) {
            _this.groups[0].list = result;
        });
    };
    DashListCtrl.prototype.starDashboard = function (dash, evt) {
        this.dashboardSrv.starDashboard(dash.id, dash.isStarred).then(function (newState) {
            dash.isStarred = newState;
        });
        if (evt) {
            evt.stopPropagation();
            evt.preventDefault();
        }
    };
    DashListCtrl.prototype.getRecentDashboards = function () {
        var _this = this;
        this.groups[1].show = this.panel.recent;
        if (!this.panel.recent) {
            return Promise.resolve();
        }
        var dashIds = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.take(app_core_services_impression_srv__WEBPACK_IMPORTED_MODULE_3__["default"].getDashboardOpened(), this.panel.limit);
        return this.backendSrv.search({ dashboardIds: dashIds, limit: this.panel.limit }).then(function (result) {
            _this.groups[1].list = dashIds
                .map(function (orderId) {
                return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.find(result, function (dashboard) {
                    return dashboard.id === orderId;
                });
            })
                .filter(function (el) {
                return el !== undefined;
            });
        });
    };
    DashListCtrl.prototype.onFolderChange = function (folder) {
        this.panel.folderId = folder.id;
        this.refresh();
    };
    DashListCtrl.templateUrl = 'module.html';
    DashListCtrl.scrollable = true;
    return DashListCtrl;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_2__["PanelCtrl"]));



/***/ }),

/***/ "./public/app/plugins/panel/gauge/GaugeMigrations.ts":
/*!***********************************************************!*\
  !*** ./public/app/plugins/panel/gauge/GaugeMigrations.ts ***!
  \***********************************************************/
/*! exports provided: gaugePanelMigrationHandler, gaugePanelChangedHandler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gaugePanelMigrationHandler", function() { return gaugePanelMigrationHandler; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gaugePanelChangedHandler", function() { return gaugePanelChangedHandler; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// This is called when the panel first loads
var gaugePanelMigrationHandler = function (panel) {
    return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatMigrationHandler"])(panel);
};
// This is called when the panel changes from another panel
var gaugePanelChangedHandler = function (options, prevPluginId, prevOptions) {
    // This handles most config changes
    var opts = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatPanelChangedHandler"])(options, prevPluginId, prevOptions);
    // Changing from angular singlestat
    if (prevPluginId === 'singlestat' && prevOptions.angular) {
        var gauge = prevOptions.angular.gauge;
        if (gauge) {
            opts.showThresholdMarkers = gauge.thresholdMarkers;
            opts.showThresholdLabels = gauge.thresholdLabels;
        }
    }
    return opts;
};


/***/ }),

/***/ "./public/app/plugins/panel/gauge/GaugePanel.tsx":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/gauge/GaugePanel.tsx ***!
  \*******************************************************/
/*! exports provided: GaugePanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GaugePanel", function() { return GaugePanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/panel/panellinks/linkSuppliers */ "./public/app/features/panel/panellinks/linkSuppliers.ts");

// Libraries

// Services & Utils

// Components



var GaugePanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GaugePanel, _super);
    function GaugePanel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.renderValue = function (value, width, height) {
            var options = _this.props.options;
            var field = value.field, display = value.display;
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DataLinksContextMenu"], { links: Object(app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_4__["getFieldLinksSupplier"])(value) }, function (_a) {
                var openMenu = _a.openMenu, targetClassName = _a.targetClassName;
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["Gauge"], { value: display, width: width, height: height, thresholds: field.thresholds, showThresholdLabels: options.showThresholdLabels, showThresholdMarkers: options.showThresholdMarkers, minValue: field.min, maxValue: field.max, theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme, onClick: openMenu, className: targetClassName }));
            }));
        };
        _this.getValues = function () {
            var _a = _this.props, data = _a.data, options = _a.options, replaceVariables = _a.replaceVariables;
            return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getFieldDisplayValues"])({
                fieldOptions: options.fieldOptions,
                replaceVariables: replaceVariables,
                theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme,
                data: data.series,
            });
        };
        return _this;
    }
    GaugePanel.prototype.render = function () {
        var _a = this.props, height = _a.height, width = _a.width, data = _a.data, renderCounter = _a.renderCounter;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["VizRepeater"], { getValues: this.getValues, renderValue: this.renderValue, width: width, height: height, source: data, renderCounter: renderCounter, orientation: _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["VizOrientation"].Auto }));
    };
    return GaugePanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/gauge/GaugePanelEditor.tsx":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/gauge/GaugePanelEditor.tsx ***!
  \*************************************************************/
/*! exports provided: GaugePanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GaugePanelEditor", function() { return GaugePanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/panel/panellinks/link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");

// Libraries



var GaugePanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GaugePanelEditor, _super);
    function GaugePanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.labelWidth = 6;
        _this.onToggleThresholdLabels = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { showThresholdLabels: !_this.props.options.showThresholdLabels }));
        };
        _this.onToggleThresholdMarkers = function () {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { showThresholdMarkers: !_this.props.options.showThresholdMarkers }));
        };
        _this.onThresholdsChanged = function (thresholds) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { thresholds: thresholds }));
        };
        _this.onValueMappingsChanged = function (mappings) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { mappings: mappings }));
        };
        _this.onDisplayOptionsChanged = function (fieldOptions, event, callback) {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { fieldOptions: fieldOptions }), callback);
        };
        _this.onDefaultsChange = function (field, event, callback) {
            _this.onDisplayOptionsChanged(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions, { defaults: field }), event, callback);
        };
        _this.onDataLinksChanged = function (links, callback) {
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions.defaults, { links: links }), undefined, callback);
        };
        return _this;
    }
    GaugePanelEditor.prototype.render = function () {
        var options = this.props.options;
        var fieldOptions = options.fieldOptions, showThresholdLabels = options.showThresholdLabels, showThresholdMarkers = options.showThresholdMarkers;
        var defaults = fieldOptions.defaults;
        var suggestions = fieldOptions.values
            ? Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_3__["getDataLinksVariableSuggestions"])(this.props.data.series)
            : Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_3__["getCalculationValueDataLinksVariableSuggestions"])(this.props.data.series);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGrid"], null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Display" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldDisplayEditor"], { onChange: this.onDisplayOptionsChanged, value: fieldOptions, labelWidth: this.labelWidth }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Labels", labelClass: "width-" + this.labelWidth, checked: showThresholdLabels, onChange: this.onToggleThresholdLabels }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Markers", labelClass: "width-" + this.labelWidth, checked: showThresholdMarkers, onChange: this.onToggleThresholdMarkers })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Field" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldPropertiesEditor"], { showMinMax: true, onChange: this.onDefaultsChange, value: defaults })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ThresholdsEditor"], { onChange: this.onThresholdsChanged, thresholds: defaults.thresholds })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ValueMappingsEditor"], { onChange: this.onValueMappingsChanged, valueMappings: defaults.mappings }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Data links" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DataLinksEditor"], { value: defaults.links, onChange: this.onDataLinksChanged, suggestions: suggestions, maxLinks: 10 }))));
    };
    return GaugePanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/gauge/module.tsx":
/*!***************************************************!*\
  !*** ./public/app/plugins/panel/gauge/module.tsx ***!
  \***************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _GaugePanelEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./GaugePanelEditor */ "./public/app/plugins/panel/gauge/GaugePanelEditor.tsx");
/* harmony import */ var _GaugePanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./GaugePanel */ "./public/app/plugins/panel/gauge/GaugePanel.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/gauge/types.ts");
/* harmony import */ var _GaugeMigrations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./GaugeMigrations */ "./public/app/plugins/panel/gauge/GaugeMigrations.ts");





var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_GaugePanel__WEBPACK_IMPORTED_MODULE_2__["GaugePanel"])
    .setDefaults(_types__WEBPACK_IMPORTED_MODULE_3__["defaults"])
    .setEditor(_GaugePanelEditor__WEBPACK_IMPORTED_MODULE_1__["GaugePanelEditor"])
    .setPanelChangeHandler(_GaugeMigrations__WEBPACK_IMPORTED_MODULE_4__["gaugePanelChangedHandler"])
    .setMigrationHandler(_GaugeMigrations__WEBPACK_IMPORTED_MODULE_4__["gaugePanelMigrationHandler"]);


/***/ }),

/***/ "./public/app/plugins/panel/gauge/types.ts":
/*!*************************************************!*\
  !*** ./public/app/plugins/panel/gauge/types.ts ***!
  \*************************************************/
/*! exports provided: standardGaugeFieldOptions, defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "standardGaugeFieldOptions", function() { return standardGaugeFieldOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _singlestat2_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../singlestat2/types */ "./public/app/plugins/panel/singlestat2/types.ts");



var standardGaugeFieldOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _singlestat2_types__WEBPACK_IMPORTED_MODULE_2__["standardFieldDisplayOptions"]);
var defaults = {
    showThresholdMarkers: true,
    showThresholdLabels: false,
    fieldOptions: standardGaugeFieldOptions,
    orientation: _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["VizOrientation"].Auto,
};


/***/ }),

/***/ "./public/app/plugins/panel/gettingstarted/GettingStarted.tsx":
/*!********************************************************************!*\
  !*** ./public/app/plugins/panel/gettingstarted/GettingStarted.tsx ***!
  \********************************************************************/
/*! exports provided: GettingStarted */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GettingStarted", function() { return GettingStarted; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/features/plugins/datasource_srv */ "./public/app/features/plugins/datasource_srv.ts");
/* harmony import */ var app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/services/backend_srv */ "./public/app/core/services/backend_srv.ts");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/dashboard/services/DashboardSrv */ "./public/app/features/dashboard/services/DashboardSrv.ts");

// Libraries





var GettingStarted = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GettingStarted, _super);
    function GettingStarted(props) {
        var _this = _super.call(this, props) || this;
        _this.stepIndex = 0;
        _this.dismiss = function () {
            var id = _this.props.id;
            var dashboard = Object(app_features_dashboard_services_DashboardSrv__WEBPACK_IMPORTED_MODULE_5__["getDashboardSrv"])().getCurrent();
            var panel = dashboard.getPanelById(id);
            dashboard.removePanel(panel);
            Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__["getBackendSrv"])()
                .request({
                method: 'PUT',
                url: '/api/user/helpflags/1',
                showSuccessAlert: false,
            })
                .then(function (res) {
                app_core_core__WEBPACK_IMPORTED_MODULE_4__["contextSrv"].user.helpFlags1 = res.helpFlags1;
            });
        };
        _this.state = {
            checksDone: false,
        };
        _this.steps = [
            {
                title: 'Install Grafana',
                icon: 'icon-gf icon-gf-check',
                href: 'http://docs.grafana.org/',
                target: '_blank',
                note: 'Review the installation docs',
                check: function () { return Promise.resolve(true); },
            },
            {
                title: 'Create your first data source',
                cta: 'Add data source',
                icon: 'gicon gicon-datasources',
                href: 'datasources/new?gettingstarted',
                check: function () {
                    return new Promise(function (resolve) {
                        resolve(Object(app_features_plugins_datasource_srv__WEBPACK_IMPORTED_MODULE_2__["getDatasourceSrv"])()
                            .getMetricSources()
                            .filter(function (item) {
                            return item.meta.builtIn !== true;
                        }).length > 0);
                    });
                },
            },
            {
                title: 'Create your first dashboard',
                cta: 'New dashboard',
                icon: 'gicon gicon-dashboard',
                href: 'dashboard/new?gettingstarted',
                check: function () {
                    return Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__["getBackendSrv"])()
                        .search({ limit: 1 })
                        .then(function (result) {
                        return result.length > 0;
                    });
                },
            },
            {
                title: 'Invite your team',
                cta: 'Add Users',
                icon: 'gicon gicon-team',
                href: 'org/users?gettingstarted',
                check: function () {
                    return Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__["getBackendSrv"])()
                        .get('/api/org/users/lookup')
                        .then(function (res) {
                        return res.length > 1;
                    });
                },
            },
            {
                title: 'Install apps & plugins',
                cta: 'Explore plugin repository',
                icon: 'gicon gicon-plugins',
                href: 'https://grafana.com/plugins?utm_source=grafana_getting_started',
                check: function () {
                    return Object(app_core_services_backend_srv__WEBPACK_IMPORTED_MODULE_3__["getBackendSrv"])()
                        .get('/api/plugins', { embedded: 0, core: 0 })
                        .then(function (plugins) {
                        return plugins.length > 0;
                    });
                },
            },
        ];
        return _this;
    }
    GettingStarted.prototype.componentDidMount = function () {
        var _this = this;
        this.stepIndex = -1;
        return this.nextStep().then(function (res) {
            _this.setState({ checksDone: true });
        });
    };
    GettingStarted.prototype.nextStep = function () {
        var _this = this;
        if (this.stepIndex === this.steps.length - 1) {
            return Promise.resolve();
        }
        this.stepIndex += 1;
        var currentStep = this.steps[this.stepIndex];
        return currentStep.check().then(function (passed) {
            if (passed) {
                currentStep.done = true;
                return _this.nextStep();
            }
            return Promise.resolve();
        });
    };
    GettingStarted.prototype.render = function () {
        var checksDone = this.state.checksDone;
        if (!checksDone) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, "checking...");
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "progress-tracker-container" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", { className: "progress-tracker-close-btn", onClick: this.dismiss },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-remove" })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "progress-tracker" }, this.steps.map(function (step, index) {
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { key: index, className: step.done ? 'progress-step completed' : 'progress-step active' },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "progress-link", href: step.href, target: step.target, title: step.note },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "progress-marker" },
                            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: step.icon })),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "progress-text" }, step.title)),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "btn-small progress-step-cta", href: step.href, target: step.target }, step.cta)));
            }))));
    };
    return GettingStarted;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/gettingstarted/module.ts":
/*!***********************************************************!*\
  !*** ./public/app/plugins/panel/gettingstarted/module.ts ***!
  \***********************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _GettingStarted__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./GettingStarted */ "./public/app/plugins/panel/gettingstarted/GettingStarted.tsx");


// Simplest possible panel plugin
var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_GettingStarted__WEBPACK_IMPORTED_MODULE_1__["GettingStarted"]);


/***/ }),

/***/ "./public/app/plugins/panel/graph/GraphContextMenu.tsx":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/graph/GraphContextMenu.tsx ***!
  \*************************************************************/
/*! exports provided: GraphContextMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphContextMenu", function() { return GraphContextMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var emotion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! emotion */ "./node_modules/emotion/dist/index.esm.js");




var GraphContextMenu = function (_a) {
    var getContextMenuSource = _a.getContextMenuSource, formatSourceDate = _a.formatSourceDate, items = _a.items, otherProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["getContextMenuSource", "formatSourceDate", "items"]);
    var theme = Object(react__WEBPACK_IMPORTED_MODULE_1__["useContext"])(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ThemeContext"]);
    var source = getContextMenuSource();
    //  Do not render items that do not have label specified
    var itemsToRender = items
        ? items.map(function (group) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, group, { items: group.items.filter(function (item) { return item.label; }) })); })
        : [];
    var renderHeader = source
        ? function () {
            if (!source) {
                return null;
            }
            var timeFormat = source.series.hasMsResolution ? 'YYYY-MM-DD HH:mm:ss.SSS' : 'YYYY-MM-DD HH:mm:ss';
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_1 || (templateObject_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n              padding: ", " ", ";\n              font-size: ", ";\n            "], ["\n              padding: ", " ", ";\n              font-size: ", ";\n            "])), theme.spacing.xs, theme.spacing.sm, theme.typography.size.sm) },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("strong", null, formatSourceDate(source.datapoint[0], timeFormat)),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["SeriesIcon"], { color: source.series.color }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: Object(emotion__WEBPACK_IMPORTED_MODULE_3__["css"])(templateObject_2 || (templateObject_2 = tslib__WEBPACK_IMPORTED_MODULE_0__["__makeTemplateObject"](["\n                  white-space: nowrap;\n                  padding-left: ", ";\n                "], ["\n                  white-space: nowrap;\n                  padding-left: ", ";\n                "])), theme.spacing.xs) }, source.series.alias))));
        }
        : null;
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ContextMenu"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, otherProps, { items: itemsToRender, renderHeader: renderHeader }));
};
var templateObject_1, templateObject_2;


/***/ }),

/***/ "./public/app/plugins/panel/graph/GraphContextMenuCtrl.ts":
/*!****************************************************************!*\
  !*** ./public/app/plugins/panel/graph/GraphContextMenuCtrl.ts ***!
  \****************************************************************/
/*! exports provided: GraphContextMenuCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphContextMenuCtrl", function() { return GraphContextMenuCtrl; });
var GraphContextMenuCtrl = /** @class */ (function () {
    function GraphContextMenuCtrl($scope) {
        var _this = this;
        this.onClose = function () {
            if (_this.scrollContextElement) {
                _this.scrollContextElement.removeEventListener('scroll', _this.onClose);
            }
            _this.scope.$apply(function () {
                _this.isVisible = false;
            });
        };
        this.toggleMenu = function (event) {
            _this.isVisible = !_this.isVisible;
            if (_this.isVisible && _this.scrollContextElement) {
                _this.scrollContextElement.addEventListener('scroll', _this.onClose);
            }
            if (_this.source) {
                _this.position = {
                    x: _this.source.pageX,
                    y: _this.source.pageY,
                };
            }
            else {
                _this.position = {
                    x: event ? event.pageX : 0,
                    y: event ? event.pageY : 0,
                };
            }
        };
        // Sets element which is considered as a scroll context of given context menu.
        // Having access to this element allows scroll event attachement for menu to be closed when user scrolls
        this.setScrollContextElement = function (el) {
            _this.scrollContextElement = el;
        };
        this.setSource = function (source) {
            _this.source = source;
        };
        this.getSource = function () {
            return _this.source;
        };
        this.setMenuItemsSupplier = function (menuItemsSupplier) {
            _this.menuItemsSupplier = menuItemsSupplier;
        };
        this.isVisible = false;
        this.scope = $scope;
    }
    return GraphContextMenuCtrl;
}());



/***/ }),

/***/ "./public/app/plugins/panel/graph/Legend/Legend.tsx":
/*!**********************************************************!*\
  !*** ./public/app/plugins/panel/graph/Legend/Legend.tsx ***!
  \**********************************************************/
/*! exports provided: GraphLegend, Legend, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphLegend", function() { return GraphLegend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Legend", function() { return Legend; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _LegendSeriesItem__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LegendSeriesItem */ "./public/app/plugins/panel/graph/Legend/LegendSeriesItem.tsx");





var GraphLegend = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GraphLegend, _super);
    function GraphLegend(props) {
        var _this = _super.call(this, props) || this;
        _this.onToggleSeries = function (series, event) {
            var hiddenSeries = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.state.hiddenSeries);
            if (event.ctrlKey || event.metaKey || event.shiftKey) {
                if (hiddenSeries[series.alias]) {
                    delete hiddenSeries[series.alias];
                }
                else {
                    hiddenSeries[series.alias] = true;
                }
            }
            else {
                hiddenSeries = _this.toggleSeriesExclusiveMode(series);
            }
            _this.setState({ hiddenSeries: hiddenSeries });
            _this.props.onToggleSeries(hiddenSeries);
        };
        _this.state = {
            hiddenSeries: _this.props.hiddenSeries,
        };
        return _this;
    }
    GraphLegend.prototype.sortLegend = function () {
        var _this = this;
        var seriesList = tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](this.props.seriesList) || [];
        if (this.props.sort && this.props[this.props.sort] && this.props.alignAsTable) {
            seriesList = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(seriesList, function (series) {
                var sort = series.stats[_this.props.sort];
                if (sort === null) {
                    sort = -Infinity;
                }
                return sort;
            });
            if (this.props.sortDesc) {
                seriesList = seriesList.reverse();
            }
        }
        return seriesList;
    };
    GraphLegend.prototype.toggleSeriesExclusiveMode = function (series) {
        var hiddenSeries = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.state.hiddenSeries);
        if (hiddenSeries[series.alias]) {
            delete hiddenSeries[series.alias];
        }
        // check if every other series is hidden
        var alreadyExclusive = this.props.seriesList.every(function (value) {
            if (value.alias === series.alias) {
                return true;
            }
            return hiddenSeries[value.alias];
        });
        if (alreadyExclusive) {
            // remove all hidden series
            this.props.seriesList.forEach(function (value) {
                delete hiddenSeries[value.alias];
            });
        }
        else {
            // hide all but this serie
            this.props.seriesList.forEach(function (value) {
                if (value.alias === series.alias) {
                    return;
                }
                hiddenSeries[value.alias] = true;
            });
        }
        return hiddenSeries;
    };
    GraphLegend.prototype.render = function () {
        var _a = this.props, optionalClass = _a.optionalClass, rightSide = _a.rightSide, sideWidth = _a.sideWidth, sort = _a.sort, sortDesc = _a.sortDesc, hideEmpty = _a.hideEmpty, hideZero = _a.hideZero, values = _a.values, min = _a.min, max = _a.max, avg = _a.avg, current = _a.current, total = _a.total;
        var seriesValuesProps = { values: values, min: min, max: max, avg: avg, current: current, total: total };
        var hiddenSeries = this.state.hiddenSeries;
        var seriesHideProps = { hideEmpty: hideEmpty, hideZero: hideZero };
        var sortProps = { sort: sort, sortDesc: sortDesc };
        var seriesList = this.sortLegend().filter(function (series) { return !series.hideFromLegend(seriesHideProps); });
        var legendClass = (this.props.alignAsTable ? 'graph-legend-table' : '') + " " + optionalClass;
        // Set min-width if side style and there is a value, otherwise remove the CSS property
        // Set width so it works with IE11
        var width = rightSide && sideWidth ? sideWidth : undefined;
        var ieWidth = rightSide && sideWidth ? sideWidth - 1 : undefined;
        var legendStyle = {
            minWidth: width,
            width: ieWidth,
        };
        var legendProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ seriesList: seriesList, hiddenSeries: hiddenSeries, onToggleSeries: this.onToggleSeries, onToggleAxis: this.props.onToggleAxis, onToggleSort: this.props.onToggleSort, onColorChange: this.props.onColorChange }, seriesValuesProps, sortProps);
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: "graph-legend-content " + legendClass, style: legendStyle }, this.props.alignAsTable ? react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(LegendTable, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, legendProps)) : react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(LegendSeriesList, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, legendProps))));
    };
    GraphLegend.defaultProps = {
        values: false,
        min: false,
        max: false,
        avg: false,
        current: false,
        total: false,
        alignAsTable: false,
        rightSide: false,
        sort: undefined,
        sortDesc: false,
        optionalClass: '',
        onToggleSeries: function () { },
        onToggleSort: function () { },
        onToggleAxis: function () { },
        onColorChange: function () { },
    };
    return GraphLegend;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));

var LegendSeriesList = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LegendSeriesList, _super);
    function LegendSeriesList() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LegendSeriesList.prototype.render = function () {
        var _this = this;
        var _a = this.props, seriesList = _a.seriesList, hiddenSeries = _a.hiddenSeries, values = _a.values, min = _a.min, max = _a.max, avg = _a.avg, current = _a.current, total = _a.total;
        var seriesValuesProps = { values: values, min: min, max: max, avg: avg, current: current, total: total };
        return seriesList.map(function (series, i) { return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_LegendSeriesItem__WEBPACK_IMPORTED_MODULE_4__["LegendItem"]
        // This trick required because TimeSeries.id is not unique (it's just TimeSeries.alias).
        // In future would be good to make id unique across the series list.
        , tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ 
            // This trick required because TimeSeries.id is not unique (it's just TimeSeries.alias).
            // In future would be good to make id unique across the series list.
            key: series.id + "-" + i, series: series, hidden: hiddenSeries[series.alias] }, seriesValuesProps, { onLabelClick: _this.props.onToggleSeries, onColorChange: _this.props.onColorChange, onToggleAxis: _this.props.onToggleAxis }))); });
    };
    return LegendSeriesList;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));
var LegendTable = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LegendTable, _super);
    function LegendTable() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onToggleSort = function (stat) {
            var sortDesc = _this.props.sortDesc;
            var sortBy = _this.props.sort;
            if (stat !== sortBy) {
                sortDesc = null;
            }
            // if already sort ascending, disable sorting
            if (sortDesc === false) {
                sortBy = null;
                sortDesc = null;
            }
            else {
                sortDesc = !sortDesc;
                sortBy = stat;
            }
            _this.props.onToggleSort(sortBy, sortDesc);
        };
        return _this;
    }
    LegendTable.prototype.render = function () {
        var _this = this;
        var seriesList = this.props.seriesList;
        var _a = this.props, values = _a.values, min = _a.min, max = _a.max, avg = _a.avg, current = _a.current, total = _a.total, sort = _a.sort, sortDesc = _a.sortDesc, hiddenSeries = _a.hiddenSeries;
        var seriesValuesProps = { values: values, min: min, max: max, avg: avg, current: current, total: total };
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("table", null,
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("colgroup", null,
                react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("col", { style: { width: '100%' } })),
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("thead", null,
                react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("tr", null,
                    react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("th", { style: { textAlign: 'left' } }),
                    _LegendSeriesItem__WEBPACK_IMPORTED_MODULE_4__["LEGEND_STATS"].map(function (statName) {
                        return seriesValuesProps[statName] && (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(LegendTableHeaderItem, { key: statName, statName: statName, sort: sort, sortDesc: sortDesc, onClick: _this.onToggleSort }));
                    }))),
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("tbody", null, seriesList.map(function (series, i) { return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_LegendSeriesItem__WEBPACK_IMPORTED_MODULE_4__["LegendItem"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ key: series.id + "-" + i, asTable: true, series: series, hidden: hiddenSeries[series.alias], onLabelClick: _this.props.onToggleSeries, onColorChange: _this.props.onColorChange, onToggleAxis: _this.props.onToggleAxis }, seriesValuesProps))); }))));
    };
    return LegendTable;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));
var LegendTableHeaderItem = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LegendTableHeaderItem, _super);
    function LegendTableHeaderItem() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onClick = function () { return _this.props.onClick(_this.props.statName); };
        return _this;
    }
    LegendTableHeaderItem.prototype.render = function () {
        var _a = this.props, statName = _a.statName, sort = _a.sort, sortDesc = _a.sortDesc;
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("th", { className: "pointer", onClick: this.onClick },
            statName,
            sort === statName && react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", { className: sortDesc ? 'fa fa-caret-down' : 'fa fa-caret-up' })));
    };
    return LegendTableHeaderItem;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));
var Legend = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Legend, _super);
    function Legend() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Legend.prototype.render = function () {
        return (react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["CustomScrollbar"], { hideHorizontalTrack: true },
            react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(GraphLegend, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.props))));
    };
    return Legend;
}(react__WEBPACK_IMPORTED_MODULE_2__["PureComponent"]));

/* harmony default export */ __webpack_exports__["default"] = (Legend);


/***/ }),

/***/ "./public/app/plugins/panel/graph/Legend/LegendSeriesItem.tsx":
/*!********************************************************************!*\
  !*** ./public/app/plugins/panel/graph/Legend/LegendSeriesItem.tsx ***!
  \********************************************************************/
/*! exports provided: LEGEND_STATS, LegendItem */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LEGEND_STATS", function() { return LEGEND_STATS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LegendItem", function() { return LegendItem; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! classnames */ "./node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var LEGEND_STATS = ['min', 'max', 'avg', 'current', 'total'];
var LegendItem = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LegendItem, _super);
    function LegendItem(props) {
        var _this = _super.call(this, props) || this;
        _this.onLabelClick = function (e) { return _this.props.onLabelClick(_this.props.series, e); };
        _this.onToggleAxis = function () {
            var yaxis = _this.state.yaxis === 2 ? 1 : 2;
            var info = { alias: _this.props.series.alias, yaxis: yaxis };
            _this.setState({ yaxis: yaxis });
            _this.props.onToggleAxis(info);
        };
        _this.onColorChange = function (color) {
            _this.props.onColorChange(_this.props.series, color);
            // Because of PureComponent nature it makes only shallow props comparison and changing of series.color doesn't run
            // component re-render. In this case we can't rely on color, selected by user, because it may be overwritten
            // by series overrides. So we need to use forceUpdate() to make sure we have proper series color.
            _this.forceUpdate();
        };
        _this.state = {
            yaxis: _this.props.series.yaxis,
        };
        return _this;
    }
    LegendItem.prototype.renderLegendValues = function () {
        var e_1, _a;
        var _b = this.props, series = _b.series, asTable = _b.asTable;
        var legendValueItems = [];
        try {
            for (var LEGEND_STATS_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](LEGEND_STATS), LEGEND_STATS_1_1 = LEGEND_STATS_1.next(); !LEGEND_STATS_1_1.done; LEGEND_STATS_1_1 = LEGEND_STATS_1.next()) {
                var valueName = LEGEND_STATS_1_1.value;
                // @ts-ignore
                if (this.props[valueName]) {
                    var valueFormatted = series.formatValue(series.stats[valueName]);
                    legendValueItems.push(react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LegendValue, { key: valueName, valueName: valueName, value: valueFormatted, asTable: asTable }));
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (LEGEND_STATS_1_1 && !LEGEND_STATS_1_1.done && (_a = LEGEND_STATS_1.return)) _a.call(LEGEND_STATS_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return legendValueItems;
    };
    LegendItem.prototype.render = function () {
        var _a = this.props, series = _a.series, values = _a.values, asTable = _a.asTable, hidden = _a.hidden;
        var seriesOptionClasses = classnames__WEBPACK_IMPORTED_MODULE_2___default()({
            'graph-legend-series-hidden': hidden,
            'graph-legend-series--right-y': series.yaxis === 2,
        });
        var valueItems = values ? this.renderLegendValues() : [];
        var seriesLabel = (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LegendSeriesLabel, { label: series.alias, color: series.color, yaxis: this.state.yaxis, onLabelClick: this.onLabelClick, onColorChange: this.onColorChange, onToggleAxis: this.onToggleAxis }));
        if (asTable) {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("tr", { className: "graph-legend-series " + seriesOptionClasses },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", null, seriesLabel),
                valueItems));
        }
        else {
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "graph-legend-series " + seriesOptionClasses },
                seriesLabel,
                valueItems));
        }
    };
    LegendItem.defaultProps = {
        asTable: false,
        hidden: false,
        onLabelClick: function () { },
        onColorChange: function () { },
        onToggleAxis: function () { },
    };
    return LegendItem;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var LegendSeriesLabel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LegendSeriesLabel, _super);
    function LegendSeriesLabel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LegendSeriesLabel.prototype.render = function () {
        var _this = this;
        var _a = this.props, label = _a.label, color = _a.color, yaxis = _a.yaxis;
        var _b = this.props, onColorChange = _b.onColorChange, onToggleAxis = _b.onToggleAxis;
        return [
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(LegendSeriesIcon, { key: "icon", color: color, yaxis: yaxis, onColorChange: onColorChange, onToggleAxis: onToggleAxis }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", { className: "graph-legend-alias pointer", title: label, key: "label", onClick: function (e) { return _this.props.onLabelClick(e); } }, label),
        ];
    };
    LegendSeriesLabel.defaultProps = {
        yaxis: undefined,
        onLabelClick: function () { },
    };
    return LegendSeriesLabel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
function SeriesIcon(_a) {
    var color = _a.color;
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", { className: "fa fa-minus pointer", style: { color: color } });
}
var LegendSeriesIcon = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LegendSeriesIcon, _super);
    function LegendSeriesIcon() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LegendSeriesIcon.prototype.render = function () {
        var _this = this;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["SeriesColorPicker"], { yaxis: this.props.yaxis, color: this.props.color, onChange: this.props.onColorChange, onToggleAxis: this.props.onToggleAxis, enableNamedColors: true }, function (_a) {
            var ref = _a.ref, showColorPicker = _a.showColorPicker, hideColorPicker = _a.hideColorPicker;
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { ref: ref, onClick: showColorPicker, onMouseLeave: hideColorPicker, className: "graph-legend-icon" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(SeriesIcon, { color: _this.props.color })));
        }));
    };
    LegendSeriesIcon.defaultProps = {
        yaxis: undefined,
        onColorChange: function () { },
        onToggleAxis: function () { },
    };
    return LegendSeriesIcon;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
function LegendValue(props) {
    var value = props.value;
    var valueName = props.valueName;
    if (props.asTable) {
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("td", { className: "graph-legend-value " + valueName }, value);
    }
    return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "graph-legend-value " + valueName }, value);
}


/***/ }),

/***/ "./public/app/plugins/panel/graph/align_yaxes.ts":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/graph/align_yaxes.ts ***!
  \*******************************************************/
/*! exports provided: alignYLevel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignYLevel", function() { return alignYLevel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


/**
 * To align two Y axes by Y level
 * @param yAxes data [{min: min_y1, min: max_y1}, {min: min_y2, max: max_y2}]
 * @param level Y level
 */
function alignYLevel(yAxes, level) {
    if (isNaN(level) || !checkCorrectAxis(yAxes)) {
        return;
    }
    var _a = tslib__WEBPACK_IMPORTED_MODULE_0__["__read"](yAxes, 2), yLeft = _a[0], yRight = _a[1];
    moveLevelToZero(yLeft, yRight, level);
    expandStuckValues(yLeft, yRight);
    // one of graphs on zero
    var zero = yLeft.min === 0 || yRight.min === 0 || yLeft.max === 0 || yRight.max === 0;
    var oneSide = checkOneSide(yLeft, yRight);
    if (zero && oneSide) {
        yLeft.min = yLeft.max > 0 ? 0 : yLeft.min;
        yLeft.max = yLeft.max > 0 ? yLeft.max : 0;
        yRight.min = yRight.max > 0 ? 0 : yRight.min;
        yRight.max = yRight.max > 0 ? yRight.max : 0;
    }
    else {
        if (checkOppositeSides(yLeft, yRight)) {
            if (yLeft.min >= 0) {
                yLeft.min = -yLeft.max;
                yRight.max = -yRight.min;
            }
            else {
                yLeft.max = -yLeft.min;
                yRight.min = -yRight.max;
            }
        }
        else {
            var rate = getRate(yLeft, yRight);
            if (oneSide) {
                // all graphs above the Y level
                if (yLeft.min > 0) {
                    yLeft.min = yLeft.max / rate;
                    yRight.min = yRight.max / rate;
                }
                else {
                    yLeft.max = yLeft.min / rate;
                    yRight.max = yRight.min / rate;
                }
            }
            else {
                if (checkTwoCross(yLeft, yRight)) {
                    yLeft.min = yRight.min ? yRight.min * rate : yLeft.min;
                    yRight.min = yLeft.min ? yLeft.min / rate : yRight.min;
                    yLeft.max = yRight.max ? yRight.max * rate : yLeft.max;
                    yRight.max = yLeft.max ? yLeft.max / rate : yRight.max;
                }
                else {
                    yLeft.min = yLeft.min > 0 ? yRight.min * rate : yLeft.min;
                    yRight.min = yRight.min > 0 ? yLeft.min / rate : yRight.min;
                    yLeft.max = yLeft.max < 0 ? yRight.max * rate : yLeft.max;
                    yRight.max = yRight.max < 0 ? yLeft.max / rate : yRight.max;
                }
            }
        }
    }
    restoreLevelFromZero(yLeft, yRight, level);
}
function expandStuckValues(yLeft, yRight) {
    // wide Y min and max using increased wideFactor
    var wideFactor = 0.25;
    if (yLeft.max === yLeft.min) {
        yLeft.min -= wideFactor;
        yLeft.max += wideFactor;
    }
    if (yRight.max === yRight.min) {
        yRight.min -= wideFactor;
        yRight.max += wideFactor;
    }
}
function moveLevelToZero(yLeft, yRight, level) {
    if (level !== 0) {
        yLeft.min -= level;
        yLeft.max -= level;
        yRight.min -= level;
        yRight.max -= level;
    }
}
function restoreLevelFromZero(yLeft, yRight, level) {
    if (level !== 0) {
        yLeft.min += level;
        yLeft.max += level;
        yRight.min += level;
        yRight.max += level;
    }
}
function checkCorrectAxis(axis) {
    return axis.length === 2 && checkCorrectAxes(axis[0]) && checkCorrectAxes(axis[1]);
}
function checkCorrectAxes(axes) {
    return 'min' in axes && 'max' in axes;
}
function checkOneSide(yLeft, yRight) {
    // on the one hand with respect to zero
    return (yLeft.min >= 0 && yRight.min >= 0) || (yLeft.max <= 0 && yRight.max <= 0);
}
function checkTwoCross(yLeft, yRight) {
    // both across zero
    return yLeft.min <= 0 && yLeft.max >= 0 && yRight.min <= 0 && yRight.max >= 0;
}
function checkOppositeSides(yLeft, yRight) {
    // on the opposite sides with respect to zero
    return (yLeft.min >= 0 && yRight.max <= 0) || (yLeft.max <= 0 && yRight.min >= 0);
}
function getRate(yLeft, yRight) {
    var rateLeft, rateRight, rate;
    if (checkTwoCross(yLeft, yRight)) {
        rateLeft = yRight.min ? yLeft.min / yRight.min : 0;
        rateRight = yRight.max ? yLeft.max / yRight.max : 0;
    }
    else {
        if (checkOneSide(yLeft, yRight)) {
            var absLeftMin = Math.abs(yLeft.min);
            var absLeftMax = Math.abs(yLeft.max);
            var absRightMin = Math.abs(yRight.min);
            var absRightMax = Math.abs(yRight.max);
            var upLeft = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.max([absLeftMin, absLeftMax]);
            var downLeft = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.min([absLeftMin, absLeftMax]);
            var upRight = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.max([absRightMin, absRightMax]);
            var downRight = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.min([absRightMin, absRightMax]);
            rateLeft = downLeft ? upLeft / downLeft : upLeft;
            rateRight = downRight ? upRight / downRight : upRight;
        }
        else {
            if (yLeft.min > 0 || yRight.min > 0) {
                rateLeft = yLeft.max / yRight.max;
                rateRight = 0;
            }
            else {
                rateLeft = 0;
                rateRight = yLeft.min / yRight.min;
            }
        }
    }
    rate = rateLeft > rateRight ? rateLeft : rateRight;
    return rate;
}


/***/ }),

/***/ "./public/app/plugins/panel/graph/axes_editor.ts":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/graph/axes_editor.ts ***!
  \*******************************************************/
/*! exports provided: AxesEditorCtrl, axesEditorComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesEditorCtrl", function() { return AxesEditorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "axesEditorComponent", function() { return axesEditorComponent; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

var AxesEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function AxesEditorCtrl($scope) {
        this.$scope = $scope;
        this.panelCtrl = $scope.ctrl;
        this.panel = this.panelCtrl.panel;
        this.$scope.ctrl = this;
        this.unitFormats = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["getValueFormats"])();
        this.logScales = {
            linear: 1,
            'log (base 2)': 2,
            'log (base 10)': 10,
            'log (base 32)': 32,
            'log (base 1024)': 1024,
        };
        this.xAxisModes = {
            Time: 'time',
            Series: 'series',
            Histogram: 'histogram',
        };
        this.xAxisStatOptions = [
            { text: 'Avg', value: 'avg' },
            { text: 'Min', value: 'min' },
            { text: 'Max', value: 'max' },
            { text: 'Total', value: 'total' },
            { text: 'Count', value: 'count' },
            { text: 'Current', value: 'current' },
        ];
        if (this.panel.xaxis.mode === 'custom') {
            if (!this.panel.xaxis.name) {
                this.panel.xaxis.name = 'specify field';
            }
        }
    }
    AxesEditorCtrl.prototype.setUnitFormat = function (axis, subItem) {
        axis.format = subItem.value;
        this.panelCtrl.render();
    };
    AxesEditorCtrl.prototype.render = function () {
        this.panelCtrl.render();
    };
    AxesEditorCtrl.prototype.xAxisModeChanged = function () {
        this.panelCtrl.processor.setPanelDefaultsForNewXAxisMode();
        this.panelCtrl.onDataFramesReceived(this.panelCtrl.dataList);
    };
    AxesEditorCtrl.prototype.xAxisValueChanged = function () {
        this.panelCtrl.onDataFramesReceived(this.panelCtrl.dataList);
    };
    return AxesEditorCtrl;
}());

/** @ngInject */
function axesEditorComponent() {
    'use strict';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'public/app/plugins/panel/graph/axes_editor.html',
        controller: AxesEditorCtrl,
    };
}


/***/ }),

/***/ "./public/app/plugins/panel/graph/data_processor.ts":
/*!**********************************************************!*\
  !*** ./public/app/plugins/panel/graph/data_processor.ts ***!
  \**********************************************************/
/*! exports provided: DataProcessor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataProcessor", function() { return DataProcessor; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_time_series2__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/time_series2 */ "./public/app/core/time_series2.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");





var DataProcessor = /** @class */ (function () {
    function DataProcessor(panel) {
        this.panel = panel;
    }
    DataProcessor.prototype.getSeriesList = function (options) {
        var list = [];
        var dataList = options.dataList, range = options.range;
        if (!dataList || !dataList.length) {
            return list;
        }
        for (var i = 0; i < dataList.length; i++) {
            var series = dataList[i];
            var timeField = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["getTimeField"])(series).timeField;
            if (!timeField) {
                continue;
            }
            var seriesName = series.name ? series.name : series.refId;
            for (var j = 0; j < series.fields.length; j++) {
                var field = series.fields[j];
                if (field.type !== _grafana_data__WEBPACK_IMPORTED_MODULE_2__["FieldType"].number) {
                    continue;
                }
                var name = field.config && field.config.title ? field.config.title : field.name;
                if (seriesName && dataList.length > 0 && name !== seriesName) {
                    name = seriesName + ' ' + name;
                }
                var datapoints = [];
                for (var r = 0; r < series.length; r++) {
                    datapoints.push([field.values.get(r), timeField.values.get(r)]);
                }
                list.push(this.toTimeSeries(field, name, i, j, datapoints, list.length, range));
            }
        }
        // Merge all the rows if we want to show a histogram
        if (this.panel.xaxis.mode === 'histogram' && !this.panel.stack && list.length > 1) {
            var first = list[0];
            first.alias = first.aliasEscaped = 'Count';
            for (var i = 1; i < list.length; i++) {
                first.datapoints = first.datapoints.concat(list[i].datapoints);
            }
            return [first];
        }
        return list;
    };
    DataProcessor.prototype.toTimeSeries = function (field, alias, dataFrameIndex, fieldIndex, datapoints, index, range) {
        var colorIndex = index % _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["colors"].length;
        var color = this.panel.aliasColors[alias] || _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["colors"][colorIndex];
        var series = new app_core_time_series2__WEBPACK_IMPORTED_MODULE_3__["default"]({
            datapoints: datapoints || [],
            alias: alias,
            color: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getColorFromHexRgbOrName"])(color, app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].theme.type),
            unit: field.config ? field.config.unit : undefined,
            dataFrameIndex: dataFrameIndex,
            fieldIndex: fieldIndex,
        });
        if (datapoints && datapoints.length > 0 && range) {
            var last = datapoints[datapoints.length - 1][1];
            var from = range.from;
            if (last - from.valueOf() < -10000) {
                series.isOutsideRange = true;
            }
        }
        return series;
    };
    DataProcessor.prototype.setPanelDefaultsForNewXAxisMode = function () {
        switch (this.panel.xaxis.mode) {
            case 'time': {
                this.panel.bars = false;
                this.panel.lines = true;
                this.panel.points = false;
                this.panel.legend.show = true;
                this.panel.tooltip.shared = true;
                this.panel.xaxis.values = [];
                break;
            }
            case 'series': {
                this.panel.bars = true;
                this.panel.lines = false;
                this.panel.points = false;
                this.panel.stack = false;
                this.panel.legend.show = false;
                this.panel.tooltip.shared = false;
                this.panel.xaxis.values = ['total'];
                break;
            }
            case 'histogram': {
                this.panel.bars = true;
                this.panel.lines = false;
                this.panel.points = false;
                this.panel.stack = false;
                this.panel.legend.show = false;
                this.panel.tooltip.shared = false;
                break;
            }
        }
    };
    DataProcessor.prototype.validateXAxisSeriesValue = function () {
        switch (this.panel.xaxis.mode) {
            case 'series': {
                if (this.panel.xaxis.values.length === 0) {
                    this.panel.xaxis.values = ['total'];
                    return;
                }
                var validOptions = this.getXAxisValueOptions({});
                var found = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(validOptions, { value: this.panel.xaxis.values[0] });
                if (!found) {
                    this.panel.xaxis.values = ['total'];
                }
                return;
            }
        }
    };
    DataProcessor.prototype.getXAxisValueOptions = function (options) {
        switch (this.panel.xaxis.mode) {
            case 'series': {
                return [
                    { text: 'Avg', value: 'avg' },
                    { text: 'Min', value: 'min' },
                    { text: 'Max', value: 'max' },
                    { text: 'Total', value: 'total' },
                    { text: 'Count', value: 'count' },
                ];
            }
        }
        return [];
    };
    DataProcessor.prototype.pluckDeep = function (obj, property) {
        var propertyParts = property.split('.');
        var value = obj;
        for (var i = 0; i < propertyParts.length; ++i) {
            if (value[propertyParts[i]]) {
                value = value[propertyParts[i]];
            }
            else {
                return undefined;
            }
        }
        return value;
    };
    return DataProcessor;
}());



/***/ }),

/***/ "./public/app/plugins/panel/graph/graph.ts":
/*!*************************************************!*\
  !*** ./public/app/plugins/panel/graph/graph.ts ***!
  \*************************************************/
/*! exports provided: GraphElement, graphDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphElement", function() { return GraphElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "graphDirective", function() { return graphDirective; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vendor/flot/jquery.flot */ "./public/vendor/flot/jquery.flot.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var vendor_flot_jquery_flot_selection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! vendor/flot/jquery.flot.selection */ "./public/vendor/flot/jquery.flot.selection.js");
/* harmony import */ var vendor_flot_jquery_flot_selection__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_selection__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var vendor_flot_jquery_flot_time__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! vendor/flot/jquery.flot.time */ "./public/vendor/flot/jquery.flot.time.js");
/* harmony import */ var vendor_flot_jquery_flot_time__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_time__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var vendor_flot_jquery_flot_stack__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! vendor/flot/jquery.flot.stack */ "./public/vendor/flot/jquery.flot.stack.js");
/* harmony import */ var vendor_flot_jquery_flot_stack__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_stack__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var vendor_flot_jquery_flot_stackpercent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! vendor/flot/jquery.flot.stackpercent */ "./public/vendor/flot/jquery.flot.stackpercent.js");
/* harmony import */ var vendor_flot_jquery_flot_stackpercent__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_stackpercent__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var vendor_flot_jquery_flot_fillbelow__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! vendor/flot/jquery.flot.fillbelow */ "./public/vendor/flot/jquery.flot.fillbelow.js");
/* harmony import */ var vendor_flot_jquery_flot_fillbelow__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_fillbelow__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var vendor_flot_jquery_flot_crosshair__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! vendor/flot/jquery.flot.crosshair */ "./public/vendor/flot/jquery.flot.crosshair.js");
/* harmony import */ var vendor_flot_jquery_flot_crosshair__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_crosshair__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var vendor_flot_jquery_flot_dashes__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! vendor/flot/jquery.flot.dashes */ "./public/vendor/flot/jquery.flot.dashes.js");
/* harmony import */ var vendor_flot_jquery_flot_dashes__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_dashes__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _jquery_flot_events__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./jquery.flot.events */ "./public/app/plugins/panel/graph/jquery.flot.events.ts");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/core/utils/ticks */ "./public/app/core/utils/ticks.ts");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var _graph_tooltip__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./graph_tooltip */ "./public/app/plugins/panel/graph/graph_tooltip.ts");
/* harmony import */ var _threshold_manager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./threshold_manager */ "./public/app/plugins/panel/graph/threshold_manager.ts");
/* harmony import */ var _time_region_manager__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./time_region_manager */ "./public/app/plugins/panel/graph/time_region_manager.ts");
/* harmony import */ var app_features_annotations_all__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! app/features/annotations/all */ "./public/app/features/annotations/all.ts");
/* harmony import */ var _histogram__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./histogram */ "./public/app/plugins/panel/graph/histogram.ts");
/* harmony import */ var _align_yaxes__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./align_yaxes */ "./public/app/plugins/panel/graph/align_yaxes.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _Legend_Legend__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Legend/Legend */ "./public/app/plugins/panel/graph/Legend/Legend.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! app/core/utils/ConfigProvider */ "./public/app/core/utils/ConfigProvider.tsx");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! app/features/panel/panellinks/linkSuppliers */ "./public/app/features/panel/panellinks/linkSuppliers.ts");




























var LegendWithThemeProvider = Object(app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_25__["provideTheme"])(_Legend_Legend__WEBPACK_IMPORTED_MODULE_23__["Legend"]);
var GraphElement = /** @class */ (function () {
    function GraphElement(scope, elem, timeSrv) {
        var _this = this;
        this.scope = scope;
        this.elem = elem;
        this.timeSrv = timeSrv;
        this.getContextMenuItemsSupplier = function (flotPosition, linksSupplier) {
            return function () {
                // Fixed context menu items
                var items = [
                    {
                        items: [
                            {
                                label: 'Add annotation',
                                icon: 'gicon gicon-annotation',
                                onClick: function () { return _this.eventManager.updateTime({ from: flotPosition.x, to: null }); },
                            },
                        ],
                    },
                ];
                if (!linksSupplier) {
                    return items;
                }
                var dataLinks = [
                    {
                        items: linksSupplier.getLinks(_this.panel.scopedVars).map(function (link) {
                            return {
                                label: link.title,
                                url: link.href,
                                target: link.target,
                                icon: "fa " + (link.target === '_self' ? 'fa-link' : 'fa-external-link'),
                            };
                        }),
                    },
                ];
                return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](items, dataLinks);
            };
        };
        this.ctrl = scope.ctrl;
        this.contextMenu = scope.ctrl.contextMenuCtrl;
        this.dashboard = this.ctrl.dashboard;
        this.panel = this.ctrl.panel;
        this.annotations = [];
        this.panelWidth = 0;
        this.eventManager = new app_features_annotations_all__WEBPACK_IMPORTED_MODULE_17__["EventManager"](this.ctrl);
        this.thresholdManager = new _threshold_manager__WEBPACK_IMPORTED_MODULE_15__["ThresholdManager"](this.ctrl);
        this.timeRegionManager = new _time_region_manager__WEBPACK_IMPORTED_MODULE_16__["TimeRegionManager"](this.ctrl, app_core_config__WEBPACK_IMPORTED_MODULE_20__["default"].theme.type);
        // @ts-ignore
        this.tooltip = new _graph_tooltip__WEBPACK_IMPORTED_MODULE_14__["default"](this.elem, this.ctrl.dashboard, this.scope, function () {
            return _this.sortedSeries;
        });
        // panel events
        this.ctrl.events.on('panel-teardown', this.onPanelTeardown.bind(this));
        this.ctrl.events.on('render', this.onRender.bind(this));
        // global events
        app_core_core__WEBPACK_IMPORTED_MODULE_13__["appEvents"].on('graph-hover', this.onGraphHover.bind(this), scope);
        app_core_core__WEBPACK_IMPORTED_MODULE_13__["appEvents"].on('graph-hover-clear', this.onGraphHoverClear.bind(this), scope);
        this.elem.bind('plotselected', this.onPlotSelected.bind(this));
        this.elem.bind('plotclick', this.onPlotClick.bind(this));
        // get graph legend element
        if (this.elem && this.elem.parent) {
            this.legendElem = this.elem.parent().find('.graph-legend')[0];
        }
    }
    GraphElement.prototype.onRender = function (renderData) {
        var _this = this;
        this.data = renderData || this.data;
        if (!this.data) {
            return;
        }
        this.annotations = this.ctrl.annotations || [];
        this.buildFlotPairs(this.data);
        var graphHeight = this.elem.height();
        Object(app_core_core__WEBPACK_IMPORTED_MODULE_13__["updateLegendValues"])(this.data, this.panel, graphHeight);
        if (!this.panel.legend.show) {
            if (this.legendElem.hasChildNodes()) {
                react_dom__WEBPACK_IMPORTED_MODULE_22___default.a.unmountComponentAtNode(this.legendElem);
            }
            this.renderPanel();
            return;
        }
        var _a = this.panel.legend, values = _a.values, min = _a.min, max = _a.max, avg = _a.avg, current = _a.current, total = _a.total;
        var _b = this.panel.legend, alignAsTable = _b.alignAsTable, rightSide = _b.rightSide, sideWidth = _b.sideWidth, sort = _b.sort, sortDesc = _b.sortDesc, hideEmpty = _b.hideEmpty, hideZero = _b.hideZero;
        var legendOptions = { alignAsTable: alignAsTable, rightSide: rightSide, sideWidth: sideWidth, sort: sort, sortDesc: sortDesc, hideEmpty: hideEmpty, hideZero: hideZero };
        var valueOptions = { values: values, min: min, max: max, avg: avg, current: current, total: total };
        var legendProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ seriesList: this.data, hiddenSeries: this.ctrl.hiddenSeries }, legendOptions, valueOptions, { onToggleSeries: this.ctrl.onToggleSeries, onToggleSort: this.ctrl.onToggleSort, onColorChange: this.ctrl.onColorChange, onToggleAxis: this.ctrl.onToggleAxis });
        var legendReactElem = react__WEBPACK_IMPORTED_MODULE_21___default.a.createElement(LegendWithThemeProvider, legendProps);
        react_dom__WEBPACK_IMPORTED_MODULE_22___default.a.render(legendReactElem, this.legendElem, function () { return _this.renderPanel(); });
    };
    GraphElement.prototype.onGraphHover = function (evt) {
        // ignore other graph hover events if shared tooltip is disabled
        if (!this.dashboard.sharedTooltipModeEnabled()) {
            return;
        }
        // ignore if we are the emitter
        if (!this.plot || evt.panel.id === this.panel.id || this.ctrl.otherPanelInFullscreenMode()) {
            return;
        }
        this.tooltip.show(evt.pos);
    };
    GraphElement.prototype.onPanelTeardown = function () {
        if (this.plot) {
            this.plot.destroy();
            this.plot = null;
        }
        this.tooltip.destroy();
        this.elem.off();
        this.elem.remove();
        react_dom__WEBPACK_IMPORTED_MODULE_22___default.a.unmountComponentAtNode(this.legendElem);
    };
    GraphElement.prototype.onGraphHoverClear = function (event, info) {
        if (this.plot) {
            this.tooltip.clear(this.plot);
        }
    };
    GraphElement.prototype.onPlotSelected = function (event, ranges) {
        var _this = this;
        if (this.panel.xaxis.mode !== 'time') {
            // Skip if panel in histogram or series mode
            this.plot.clearSelection();
            return;
        }
        if ((ranges.ctrlKey || ranges.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
            // Add annotation
            setTimeout(function () {
                _this.eventManager.updateTime(ranges.xaxis);
            }, 100);
        }
        else {
            this.scope.$apply(function () {
                _this.timeSrv.setTime({
                    from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_26__["toUtc"])(ranges.xaxis.from),
                    to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_26__["toUtc"])(ranges.xaxis.to),
                });
            });
        }
    };
    GraphElement.prototype.onPlotClick = function (event, pos, item) {
        var _this = this;
        var scrollContextElement = this.elem.closest('.view') ? this.elem.closest('.view').get()[0] : null;
        var contextMenuSourceItem = item;
        if (this.panel.xaxis.mode !== 'time') {
            // Skip if panel in histogram or series mode
            return;
        }
        if ((pos.ctrlKey || pos.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) {
            // Skip if range selected (added in "plotselected" event handler)
            if (pos.x !== pos.x1) {
                return;
            }
            setTimeout(function () {
                _this.eventManager.updateTime({ from: pos.x, to: null });
            }, 100);
            return;
        }
        else {
            this.tooltip.clear(this.plot);
            var linksSupplier_1;
            if (item) {
                // pickup y-axis index to know which field's config to apply
                var yAxisConfig = this.panel.yaxes[item.series.yaxis.n === 2 ? 1 : 0];
                var fieldConfig = {
                    decimals: yAxisConfig.decimals,
                    links: this.panel.options.dataLinks || [],
                };
                var dataFrame = this.ctrl.dataList[item.series.dataFrameIndex];
                var field = dataFrame.fields[item.series.fieldIndex];
                var fieldDisplay = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_24__["getDisplayProcessor"])({
                    config: fieldConfig,
                    theme: Object(app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_25__["getCurrentTheme"])(),
                })(field.values.get(item.dataIndex));
                linksSupplier_1 = this.panel.options.dataLinks
                    ? Object(app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_27__["getFieldLinksSupplier"])({
                        display: fieldDisplay,
                        name: field.name,
                        view: new _grafana_data__WEBPACK_IMPORTED_MODULE_26__["DataFrameView"](dataFrame),
                        rowIndex: item.dataIndex,
                        colIndex: item.series.fieldIndex,
                        field: fieldConfig,
                    })
                    : undefined;
            }
            this.scope.$apply(function () {
                // Setting nearest CustomScrollbar element as a scroll context for graph context menu
                _this.contextMenu.setScrollContextElement(scrollContextElement);
                _this.contextMenu.setSource(contextMenuSourceItem);
                _this.contextMenu.setMenuItemsSupplier(_this.getContextMenuItemsSupplier(pos, linksSupplier_1));
                _this.contextMenu.toggleMenu(pos);
            });
        }
    };
    GraphElement.prototype.shouldAbortRender = function () {
        if (!this.data) {
            return true;
        }
        if (this.panelWidth === 0) {
            return true;
        }
        return false;
    };
    GraphElement.prototype.drawHook = function (plot) {
        // add left axis labels
        if (this.panel.yaxes[0].label && this.panel.yaxes[0].show) {
            jquery__WEBPACK_IMPORTED_MODULE_10___default()("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
                .text(this.panel.yaxes[0].label)
                .appendTo(this.elem);
        }
        // add right axis labels
        if (this.panel.yaxes[1].label && this.panel.yaxes[1].show) {
            jquery__WEBPACK_IMPORTED_MODULE_10___default()("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
                .text(this.panel.yaxes[1].label)
                .appendTo(this.elem);
        }
        if (this.ctrl.dataWarning) {
            jquery__WEBPACK_IMPORTED_MODULE_10___default()("<div class=\"datapoints-warning flot-temp-elem\">" + this.ctrl.dataWarning.title + "</div>").appendTo(this.elem);
        }
        this.thresholdManager.draw(plot);
        this.timeRegionManager.draw(plot);
    };
    GraphElement.prototype.processOffsetHook = function (plot, gridMargin) {
        var left = this.panel.yaxes[0];
        var right = this.panel.yaxes[1];
        if (left.show && left.label) {
            gridMargin.left = 20;
        }
        if (right.show && right.label) {
            gridMargin.right = 20;
        }
        // apply y-axis min/max options
        var yaxis = plot.getYAxes();
        for (var i = 0; i < yaxis.length; i++) {
            var axis = yaxis[i];
            var panelOptions = this.panel.yaxes[i];
            axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
            axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
        }
    };
    GraphElement.prototype.processRangeHook = function (plot) {
        var yAxes = plot.getYAxes();
        var align = this.panel.yaxis.align || false;
        if (yAxes.length > 1 && align === true) {
            var level = this.panel.yaxis.alignLevel || 0;
            Object(_align_yaxes__WEBPACK_IMPORTED_MODULE_19__["alignYLevel"])(yAxes, parseFloat(level));
        }
    };
    // Series could have different timeSteps,
    // let's find the smallest one so that bars are correctly rendered.
    // In addition, only take series which are rendered as bars for this.
    GraphElement.prototype.getMinTimeStepOfSeries = function (data) {
        var min = Number.MAX_VALUE;
        for (var i = 0; i < data.length; i++) {
            if (!data[i].stats.timeStep) {
                continue;
            }
            if (this.panel.bars) {
                if (data[i].bars && data[i].bars.show === false) {
                    continue;
                }
            }
            else {
                if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
                    continue;
                }
            }
            if (data[i].stats.timeStep < min) {
                min = data[i].stats.timeStep;
            }
        }
        return min;
    };
    // Function for rendering panel
    GraphElement.prototype.renderPanel = function () {
        this.panelWidth = this.elem.width();
        if (this.shouldAbortRender()) {
            return;
        }
        // give space to alert editing
        this.thresholdManager.prepare(this.elem, this.data);
        // un-check dashes if lines are unchecked
        this.panel.dashes = this.panel.lines ? this.panel.dashes : false;
        // Populate element
        var options = this.buildFlotOptions(this.panel);
        this.prepareXAxis(options, this.panel);
        this.configureYAxisOptions(this.data, options);
        this.thresholdManager.addFlotOptions(options, this.panel);
        this.timeRegionManager.addFlotOptions(options, this.panel);
        this.eventManager.addFlotEvents(this.annotations, options);
        this.sortedSeries = this.sortSeries(this.data, this.panel);
        this.callPlot(options, true);
    };
    GraphElement.prototype.buildFlotPairs = function (data) {
        for (var i = 0; i < data.length; i++) {
            var series = data[i];
            series.data = series.getFlotPairs(series.nullPointMode || this.panel.nullPointMode);
            if (series.transform === 'constant') {
                series.data = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_24__["getFlotPairsConstant"])(series.data, this.ctrl.range);
            }
            // if hidden remove points and disable stack
            if (this.ctrl.hiddenSeries[series.alias]) {
                series.data = [];
                series.stack = false;
            }
        }
    };
    GraphElement.prototype.prepareXAxis = function (options, panel) {
        switch (panel.xaxis.mode) {
            case 'series': {
                options.series.bars.barWidth = 0.7;
                options.series.bars.align = 'center';
                for (var i = 0; i < this.data.length; i++) {
                    var series = this.data[i];
                    series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
                }
                this.addXSeriesAxis(options);
                break;
            }
            case 'histogram': {
                var bucketSize = void 0;
                if (this.data.length) {
                    var histMin = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.min(lodash__WEBPACK_IMPORTED_MODULE_11___default.a.map(this.data, function (s) { return s.stats.min; }));
                    var histMax = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.max(lodash__WEBPACK_IMPORTED_MODULE_11___default.a.map(this.data, function (s) { return s.stats.max; }));
                    var ticks = panel.xaxis.buckets || this.panelWidth / 50;
                    if (panel.xaxis.min != null) {
                        var isInvalidXaxisMin = Object(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_12__["tickStep"])(panel.xaxis.min, histMax, ticks) <= 0;
                        histMin = isInvalidXaxisMin ? histMin : panel.xaxis.min;
                    }
                    if (panel.xaxis.max != null) {
                        var isInvalidXaxisMax = Object(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_12__["tickStep"])(histMin, panel.xaxis.max, ticks) <= 0;
                        histMax = isInvalidXaxisMax ? histMax : panel.xaxis.max;
                    }
                    bucketSize = Object(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_12__["tickStep"])(histMin, histMax, ticks);
                    options.series.bars.barWidth = bucketSize * 0.8;
                    this.data = Object(_histogram__WEBPACK_IMPORTED_MODULE_18__["convertToHistogramData"])(this.data, bucketSize, this.ctrl.hiddenSeries, histMin, histMax);
                }
                else {
                    bucketSize = 0;
                }
                this.addXHistogramAxis(options, bucketSize);
                break;
            }
            case 'table': {
                options.series.bars.barWidth = 0.7;
                options.series.bars.align = 'center';
                this.addXTableAxis(options);
                break;
            }
            default: {
                options.series.bars.barWidth = this.getMinTimeStepOfSeries(this.data) / 1.5;
                this.addTimeAxis(options);
                break;
            }
        }
    };
    GraphElement.prototype.callPlot = function (options, incrementRenderCounter) {
        try {
            this.plot = jquery__WEBPACK_IMPORTED_MODULE_10___default.a.plot(this.elem, this.sortedSeries, options);
            if (this.ctrl.renderError) {
                delete this.ctrl.error;
                delete this.ctrl.inspector;
            }
        }
        catch (e) {
            console.log('flotcharts error', e);
            this.ctrl.error = e.message || 'Render Error';
            this.ctrl.renderError = true;
            this.ctrl.inspector = { error: e };
        }
        if (incrementRenderCounter) {
            this.ctrl.renderingCompleted();
        }
    };
    GraphElement.prototype.buildFlotOptions = function (panel) {
        var gridColor = '#c8c8c8';
        if (app_core_config__WEBPACK_IMPORTED_MODULE_20__["default"].bootData.user.lightTheme === true) {
            gridColor = '#a1a1a1';
        }
        var stack = panel.stack ? true : null;
        var options = {
            hooks: {
                draw: [this.drawHook.bind(this)],
                processOffset: [this.processOffsetHook.bind(this)],
                processRange: [this.processRangeHook.bind(this)],
            },
            legend: { show: false },
            series: {
                stackpercent: panel.stack ? panel.percentage : false,
                stack: panel.percentage ? null : stack,
                lines: {
                    show: panel.lines,
                    zero: false,
                    fill: this.translateFillOption(panel.fill),
                    fillColor: this.getFillGradient(panel.fillGradient),
                    lineWidth: panel.dashes ? 0 : panel.linewidth,
                    steps: panel.steppedLine,
                },
                dashes: {
                    show: panel.dashes,
                    lineWidth: panel.linewidth,
                    dashLength: [panel.dashLength, panel.spaceLength],
                },
                bars: {
                    show: panel.bars,
                    fill: 1,
                    barWidth: 1,
                    zero: false,
                    lineWidth: 0,
                },
                points: {
                    show: panel.points,
                    fill: 1,
                    fillColor: false,
                    radius: panel.points ? panel.pointradius : 2,
                },
                shadowSize: 0,
            },
            yaxes: [],
            xaxis: {},
            grid: {
                minBorderMargin: 0,
                markings: [],
                backgroundColor: null,
                borderWidth: 0,
                hoverable: true,
                clickable: true,
                color: gridColor,
                margin: { left: 0, right: 0 },
                labelMarginX: 0,
                mouseActiveRadius: 30,
            },
            selection: {
                mode: 'x',
                color: '#666',
            },
            crosshair: {
                mode: 'x',
            },
        };
        return options;
    };
    GraphElement.prototype.sortSeries = function (series, panel) {
        var sortBy = panel.legend.sort;
        var sortOrder = panel.legend.sortDesc;
        var haveSortBy = sortBy !== null && sortBy !== undefined && panel.legend[sortBy];
        var haveSortOrder = sortOrder !== null && sortOrder !== undefined;
        var shouldSortBy = panel.stack && haveSortBy && haveSortOrder && panel.legend.alignAsTable;
        var sortDesc = panel.legend.sortDesc === true ? -1 : 1;
        if (shouldSortBy) {
            return lodash__WEBPACK_IMPORTED_MODULE_11___default.a.sortBy(series, function (s) { return s.stats[sortBy] * sortDesc; });
        }
        else {
            return lodash__WEBPACK_IMPORTED_MODULE_11___default.a.sortBy(series, function (s) { return s.zindex; });
        }
    };
    GraphElement.prototype.getFillGradient = function (amount) {
        if (!amount) {
            return null;
        }
        return {
            colors: [{ opacity: 0.0 }, { opacity: amount / 10 }],
        };
    };
    GraphElement.prototype.translateFillOption = function (fill) {
        if (this.panel.percentage && this.panel.stack) {
            return fill === 0 ? 0.001 : fill / 10;
        }
        else {
            return fill / 10;
        }
    };
    GraphElement.prototype.addTimeAxis = function (options) {
        var ticks = this.panelWidth / 100;
        var min = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
        var max = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
        options.xaxis = {
            timezone: this.dashboard.getTimezone(),
            show: this.panel.xaxis.show,
            mode: 'time',
            min: min,
            max: max,
            label: 'Datetime',
            ticks: ticks,
            timeformat: this.time_format(ticks, min, max),
        };
    };
    GraphElement.prototype.addXSeriesAxis = function (options) {
        var ticks = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.map(this.data, function (series, index) {
            return [index + 1, series.alias];
        });
        options.xaxis = {
            timezone: this.dashboard.getTimezone(),
            show: this.panel.xaxis.show,
            mode: null,
            min: 0,
            max: ticks.length + 1,
            label: 'Datetime',
            ticks: ticks,
        };
    };
    GraphElement.prototype.addXHistogramAxis = function (options, bucketSize) {
        var e_1, _a, e_2, _b;
        var ticks;
        var min;
        var max;
        var defaultTicks = this.panelWidth / 50;
        if (this.data.length && bucketSize) {
            var tickValues = [];
            try {
                for (var _c = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.data), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var d = _d.value;
                    try {
                        for (var _e = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](d.data)), _f = _e.next(); !_f.done; _f = _e.next()) {
                            var point = _f.value;
                            tickValues[point[0]] = true;
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
                }
                finally { if (e_1) throw e_1.error; }
            }
            ticks = Object.keys(tickValues).map(function (v) { return Number(v); });
            min = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.min(ticks);
            max = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.max(ticks);
            // Adjust tick step
            var tickStep_1 = bucketSize;
            var ticksNum = Math.floor((max - min) / tickStep_1);
            while (ticksNum > defaultTicks) {
                tickStep_1 = tickStep_1 * 2;
                ticksNum = Math.ceil((max - min) / tickStep_1);
            }
            // Expand ticks for pretty view
            min = Math.floor(min / tickStep_1) * tickStep_1;
            // 1.01 is 101% - ensure we have enough space for last bar
            max = Math.ceil((max * 1.01) / tickStep_1) * tickStep_1;
            ticks = [];
            for (var i = min; i <= max; i += tickStep_1) {
                ticks.push(i);
            }
        }
        else {
            // Set defaults if no data
            ticks = defaultTicks / 2;
            min = 0;
            max = 1;
        }
        options.xaxis = {
            timezone: this.dashboard.getTimezone(),
            show: this.panel.xaxis.show,
            mode: null,
            min: min,
            max: max,
            label: 'Histogram',
            ticks: ticks,
        };
        // Use 'short' format for histogram values
        this.configureAxisMode(options.xaxis, 'short');
    };
    GraphElement.prototype.addXTableAxis = function (options) {
        var ticks = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.map(this.data, function (series, seriesIndex) {
            return lodash__WEBPACK_IMPORTED_MODULE_11___default.a.map(series.datapoints, function (point, pointIndex) {
                var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
                return [tickIndex + 1, point[1]];
            });
        });
        // @ts-ignore, potential bug? is this _.flattenDeep?
        ticks = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.flatten(ticks, true);
        options.xaxis = {
            timezone: this.dashboard.getTimezone(),
            show: this.panel.xaxis.show,
            mode: null,
            min: 0,
            max: ticks.length + 1,
            label: 'Datetime',
            ticks: ticks,
        };
    };
    GraphElement.prototype.configureYAxisOptions = function (data, options) {
        var defaults = {
            position: 'left',
            show: this.panel.yaxes[0].show,
            index: 1,
            logBase: this.panel.yaxes[0].logBase || 1,
            min: this.parseNumber(this.panel.yaxes[0].min),
            max: this.parseNumber(this.panel.yaxes[0].max),
            tickDecimals: this.panel.yaxes[0].decimals,
        };
        options.yaxes.push(defaults);
        if (lodash__WEBPACK_IMPORTED_MODULE_11___default.a.find(data, { yaxis: 2 })) {
            var secondY = lodash__WEBPACK_IMPORTED_MODULE_11___default.a.clone(defaults);
            secondY.index = 2;
            secondY.show = this.panel.yaxes[1].show;
            secondY.logBase = this.panel.yaxes[1].logBase || 1;
            secondY.position = 'right';
            secondY.min = this.parseNumber(this.panel.yaxes[1].min);
            secondY.max = this.parseNumber(this.panel.yaxes[1].max);
            secondY.tickDecimals = this.panel.yaxes[1].decimals;
            options.yaxes.push(secondY);
            this.applyLogScale(options.yaxes[1], data);
            this.configureAxisMode(options.yaxes[1], this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[1].format);
        }
        this.applyLogScale(options.yaxes[0], data);
        this.configureAxisMode(options.yaxes[0], this.panel.percentage && this.panel.stack ? 'percent' : this.panel.yaxes[0].format);
    };
    GraphElement.prototype.parseNumber = function (value) {
        if (value === null || typeof value === 'undefined') {
            return null;
        }
        return lodash__WEBPACK_IMPORTED_MODULE_11___default.a.toNumber(value);
    };
    GraphElement.prototype.applyLogScale = function (axis, data) {
        if (axis.logBase === 1) {
            return;
        }
        var minSetToZero = axis.min === 0;
        if (axis.min < Number.MIN_VALUE) {
            axis.min = null;
        }
        if (axis.max < Number.MIN_VALUE) {
            axis.max = null;
        }
        var series, i;
        var max = axis.max, min = axis.min;
        for (i = 0; i < data.length; i++) {
            series = data[i];
            if (series.yaxis === axis.index) {
                if (!max || max < series.stats.max) {
                    max = series.stats.max;
                }
                if (!min || min > series.stats.logmin) {
                    min = series.stats.logmin;
                }
            }
        }
        axis.transform = function (v) {
            return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
        };
        axis.inverseTransform = function (v) {
            return Math.pow(axis.logBase, v);
        };
        if (!max && !min) {
            max = axis.inverseTransform(+2);
            min = axis.inverseTransform(-2);
        }
        else if (!max) {
            max = min * axis.inverseTransform(+4);
        }
        else if (!min) {
            min = max * axis.inverseTransform(-4);
        }
        if (axis.min) {
            min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
        }
        else {
            min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
        }
        if (axis.max) {
            max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
        }
        else {
            max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
        }
        if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
            return;
        }
        if (Number.isFinite(min) && Number.isFinite(max)) {
            if (minSetToZero) {
                axis.min = 0.1;
                min = 1;
            }
            axis.ticks = this.generateTicksForLogScaleYAxis(min, max, axis.logBase);
            if (minSetToZero) {
                axis.ticks.unshift(0.1);
            }
            if (axis.ticks[axis.ticks.length - 1] > axis.max) {
                axis.max = axis.ticks[axis.ticks.length - 1];
            }
        }
        else {
            axis.ticks = [1, 2];
            delete axis.min;
            delete axis.max;
        }
    };
    GraphElement.prototype.generateTicksForLogScaleYAxis = function (min, max, logBase) {
        var ticks = [];
        var nextTick;
        for (nextTick = min; nextTick <= max; nextTick *= logBase) {
            ticks.push(nextTick);
        }
        var maxNumTicks = Math.ceil(this.ctrl.height / 25);
        var numTicks = ticks.length;
        if (numTicks > maxNumTicks) {
            var factor = Math.ceil(numTicks / maxNumTicks) * logBase;
            ticks = [];
            for (nextTick = min; nextTick <= max * factor; nextTick *= factor) {
                ticks.push(nextTick);
            }
        }
        return ticks;
    };
    GraphElement.prototype.configureAxisMode = function (axis, format) {
        axis.tickFormatter = function (val, axis) {
            var formatter = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_24__["getValueFormat"])(format);
            if (!formatter) {
                throw new Error("Unit '" + format + "' is not supported");
            }
            return formatter(val, axis.tickDecimals, axis.scaledDecimals);
        };
    };
    GraphElement.prototype.time_format = function (ticks, min, max) {
        if (min && max && ticks) {
            var range = max - min;
            var secPerTick = range / ticks / 1000;
            // Need have 10 millisecond margin on the day range
            // As sometimes last 24 hour dashboard evaluates to more than 86400000
            var oneDay = 86400010;
            var oneYear = 31536000000;
            if (secPerTick <= 45) {
                return '%H:%M:%S';
            }
            if (secPerTick <= 7200 || range <= oneDay) {
                return '%H:%M';
            }
            if (secPerTick <= 80000) {
                return '%m/%d %H:%M';
            }
            if (secPerTick <= 2419200 || range <= oneYear) {
                return '%m/%d';
            }
            return '%Y-%m';
        }
        return '%H:%M';
    };
    return GraphElement;
}());
/** @ngInject */
function graphDirective(timeSrv, popoverSrv, contextSrv) {
    return {
        restrict: 'A',
        template: '',
        link: function (scope, elem) {
            return new GraphElement(scope, elem, timeSrv);
        },
    };
}
app_core_core__WEBPACK_IMPORTED_MODULE_13__["coreModule"].directive('grafanaGraph', graphDirective);



/***/ }),

/***/ "./public/app/plugins/panel/graph/graph_tooltip.ts":
/*!*********************************************************!*\
  !*** ./public/app/plugins/panel/graph/graph_tooltip.ts ***!
  \*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GraphTooltip; });
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");


function GraphTooltip(elem, dashboard, scope, getSeriesFn) {
    var self = this;
    var ctrl = scope.ctrl;
    var panel = ctrl.panel;
    var $tooltip = jquery__WEBPACK_IMPORTED_MODULE_0___default()('<div class="graph-tooltip">');
    this.destroy = function () {
        $tooltip.remove();
    };
    this.findHoverIndexFromDataPoints = function (posX, series, last) {
        var ps = series.datapoints.pointsize;
        var initial = last * ps;
        var len = series.datapoints.points.length;
        var j;
        for (j = initial; j < len; j += ps) {
            // Special case of a non stepped line, highlight the very last point just before a null point
            if ((!series.lines.steps && series.datapoints.points[initial] != null && series.datapoints.points[j] == null) ||
                //normal case
                series.datapoints.points[j] > posX) {
                return Math.max(j - ps, 0) / ps;
            }
        }
        return j / ps - 1;
    };
    this.findHoverIndexFromData = function (posX, series) {
        var lower = 0;
        var upper = series.data.length - 1;
        var middle;
        while (true) {
            if (lower > upper) {
                return Math.max(upper, 0);
            }
            middle = Math.floor((lower + upper) / 2);
            if (series.data[middle][0] === posX) {
                return middle;
            }
            else if (series.data[middle][0] < posX) {
                lower = middle + 1;
            }
            else {
                upper = middle - 1;
            }
        }
    };
    this.renderAndShow = function (absoluteTime, innerHtml, pos, xMode) {
        if (xMode === 'time') {
            innerHtml = '<div class="graph-tooltip-time">' + absoluteTime + '</div>' + innerHtml;
        }
        $tooltip.html(innerHtml).place_tt(pos.pageX + 20, pos.pageY);
    };
    this.getMultiSeriesPlotHoverInfo = function (seriesList, pos) {
        var value, i, series, hoverIndex, hoverDistance, pointTime, yaxis;
        // 3 sub-arrays, 1st for hidden series, 2nd for left yaxis, 3rd for right yaxis.
        var results = [[], [], []];
        //now we know the current X (j) position for X and Y values
        var lastValue = 0; //needed for stacked values
        var minDistance, minTime;
        for (i = 0; i < seriesList.length; i++) {
            series = seriesList[i];
            if (!series.data.length || (panel.legend.hideEmpty && series.allIsNull)) {
                // Init value so that it does not brake series sorting
                results[0].push({ hidden: true, value: 0 });
                continue;
            }
            if (!series.data.length || (panel.legend.hideZero && series.allIsZero)) {
                // Init value so that it does not brake series sorting
                results[0].push({ hidden: true, value: 0 });
                continue;
            }
            if (series.hideTooltip) {
                results[0].push({ hidden: true, value: 0 });
                continue;
            }
            hoverIndex = this.findHoverIndexFromData(pos.x, series);
            hoverDistance = pos.x - series.data[hoverIndex][0];
            pointTime = series.data[hoverIndex][0];
            // Take the closest point before the cursor, or if it does not exist, the closest after
            if (!minDistance ||
                (hoverDistance >= 0 && (hoverDistance < minDistance || minDistance < 0)) ||
                (hoverDistance < 0 && hoverDistance > minDistance)) {
                minDistance = hoverDistance;
                minTime = pointTime;
            }
            if (series.stack) {
                if (panel.tooltip.value_type === 'individual') {
                    value = series.data[hoverIndex][1];
                }
                else if (!series.stack) {
                    value = series.data[hoverIndex][1];
                }
                else {
                    lastValue += series.data[hoverIndex][1];
                    value = lastValue;
                }
            }
            else {
                value = series.data[hoverIndex][1];
            }
            // Highlighting multiple Points depending on the plot type
            if (series.lines.steps || series.stack) {
                // stacked and steppedLine plots can have series with different length.
                // Stacked series can increase its length on each new stacked serie if null points found,
                // to speed the index search we begin always on the last found hoverIndex.
                hoverIndex = this.findHoverIndexFromDataPoints(pos.x, series, hoverIndex);
            }
            // Be sure we have a yaxis so that it does not brake series sorting
            yaxis = 0;
            if (series.yaxis) {
                yaxis = series.yaxis.n;
            }
            results[yaxis].push({
                value: value,
                hoverIndex: hoverIndex,
                color: series.color,
                label: series.aliasEscaped,
                time: pointTime,
                distance: hoverDistance,
                index: i,
            });
        }
        // Contat the 3 sub-arrays
        results = results[0].concat(results[1], results[2]);
        // Time of the point closer to pointer
        results.time = minTime;
        return results;
    };
    elem.mouseleave(function () {
        if (panel.tooltip.shared) {
            var plot = elem.data().plot;
            if (plot) {
                $tooltip.detach();
                plot.unhighlight();
            }
        }
        app_core_core__WEBPACK_IMPORTED_MODULE_1__["appEvents"].emit('graph-hover-clear');
    });
    elem.bind('plothover', function (event, pos, item) {
        self.show(pos, item);
        // broadcast to other graph panels that we are hovering!
        pos.panelRelY = (pos.pageY - elem.offset().top) / elem.height();
        app_core_core__WEBPACK_IMPORTED_MODULE_1__["appEvents"].emit('graph-hover', { pos: pos, panel: panel });
    });
    elem.bind('plotclick', function (event, pos, item) {
        app_core_core__WEBPACK_IMPORTED_MODULE_1__["appEvents"].emit('graph-click', { pos: pos, panel: panel, item: item });
    });
    this.clear = function (plot) {
        $tooltip.detach();
        plot.clearCrosshair();
        plot.unhighlight();
    };
    this.show = function (pos, item) {
        var plot = elem.data().plot;
        var plotData = plot.getData();
        var xAxes = plot.getXAxes();
        var xMode = xAxes[0].options.mode;
        var seriesList = getSeriesFn();
        var allSeriesMode = panel.tooltip.shared;
        var group, value, absoluteTime, hoverInfo, i, series, seriesHtml, tooltipFormat;
        // if panelRelY is defined another panel wants us to show a tooltip
        // get pageX from position on x axis and pageY from relative position in original panel
        if (pos.panelRelY) {
            var pointOffset = plot.pointOffset({ x: pos.x });
            if (Number.isNaN(pointOffset.left) || pointOffset.left < 0 || pointOffset.left > elem.width()) {
                self.clear(plot);
                return;
            }
            pos.pageX = elem.offset().left + pointOffset.left;
            pos.pageY = elem.offset().top + elem.height() * pos.panelRelY;
            var isVisible = pos.pageY >= jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).scrollTop() && pos.pageY <= jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).innerHeight() + jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).scrollTop();
            if (!isVisible) {
                self.clear(plot);
                return;
            }
            plot.setCrosshair(pos);
            allSeriesMode = true;
            if (dashboard.sharedCrosshairModeOnly()) {
                // if only crosshair mode we are done
                return;
            }
        }
        if (seriesList.length === 0) {
            return;
        }
        if (seriesList[0].hasMsResolution) {
            tooltipFormat = 'YYYY-MM-DD HH:mm:ss.SSS';
        }
        else {
            tooltipFormat = 'YYYY-MM-DD HH:mm:ss';
        }
        if (allSeriesMode) {
            plot.unhighlight();
            var seriesHoverInfo = self.getMultiSeriesPlotHoverInfo(plotData, pos);
            seriesHtml = '';
            absoluteTime = dashboard.formatDate(seriesHoverInfo.time, tooltipFormat);
            // Dynamically reorder the hovercard for the current time point if the
            // option is enabled.
            if (panel.tooltip.sort === 2) {
                seriesHoverInfo.sort(function (a, b) {
                    return b.value - a.value;
                });
            }
            else if (panel.tooltip.sort === 1) {
                seriesHoverInfo.sort(function (a, b) {
                    return a.value - b.value;
                });
            }
            for (i = 0; i < seriesHoverInfo.length; i++) {
                hoverInfo = seriesHoverInfo[i];
                if (hoverInfo.hidden) {
                    continue;
                }
                var highlightClass = '';
                if (item && hoverInfo.index === item.seriesIndex) {
                    highlightClass = 'graph-tooltip-list-item--highlight';
                }
                series = seriesList[hoverInfo.index];
                value = series.formatValue(hoverInfo.value);
                seriesHtml +=
                    '<div class="graph-tooltip-list-item ' + highlightClass + '"><div class="graph-tooltip-series-name">';
                seriesHtml +=
                    '<i class="fa fa-minus" style="color:' + hoverInfo.color + ';"></i> ' + hoverInfo.label + ':</div>';
                seriesHtml += '<div class="graph-tooltip-value">' + value + '</div></div>';
                plot.highlight(hoverInfo.index, hoverInfo.hoverIndex);
            }
            self.renderAndShow(absoluteTime, seriesHtml, pos, xMode);
        }
        else if (item) {
            // single series tooltip
            series = seriesList[item.seriesIndex];
            group = '<div class="graph-tooltip-list-item"><div class="graph-tooltip-series-name">';
            group +=
                '<i class="fa fa-minus" style="color:' + item.series.color + ';"></i> ' + series.aliasEscaped + ':</div>';
            if (panel.stack && panel.tooltip.value_type === 'individual') {
                value = item.datapoint[1] - item.datapoint[2];
            }
            else {
                value = item.datapoint[1];
            }
            value = series.formatValue(value);
            absoluteTime = dashboard.formatDate(item.datapoint[0], tooltipFormat);
            group += '<div class="graph-tooltip-value">' + value + '</div>';
            self.renderAndShow(absoluteTime, group, pos, xMode);
        }
        else {
            // no hit
            $tooltip.detach();
        }
    };
}


/***/ }),

/***/ "./public/app/plugins/panel/graph/histogram.ts":
/*!*****************************************************!*\
  !*** ./public/app/plugins/panel/graph/histogram.ts ***!
  \*****************************************************/
/*! exports provided: getSeriesValues, convertValuesToHistogram, convertToHistogramData */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSeriesValues", function() { return getSeriesValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertValuesToHistogram", function() { return convertValuesToHistogram; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToHistogramData", function() { return convertToHistogramData; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

/**
 * Convert series into array of series values.
 * @param data Array of series
 */
function getSeriesValues(dataList) {
    var VALUE_INDEX = 0;
    var values = [];
    // Count histogam stats
    for (var i = 0; i < dataList.length; i++) {
        var series = dataList[i];
        var datapoints = series.datapoints;
        for (var j = 0; j < datapoints.length; j++) {
            if (datapoints[j][VALUE_INDEX] !== null) {
                values.push(datapoints[j][VALUE_INDEX]);
            }
        }
    }
    return values;
}
/**
 * Convert array of values into timeseries-like histogram:
 * [[val_1, count_1], [val_2, count_2], ..., [val_n, count_n]]
 * @param values
 * @param bucketSize
 */
function convertValuesToHistogram(values, bucketSize, min, max) {
    var histogram = {};
    var minBound = getBucketBound(min, bucketSize);
    var maxBound = getBucketBound(max, bucketSize);
    var bound = minBound;
    var n = 0;
    while (bound <= maxBound) {
        histogram[bound] = 0;
        bound = minBound + bucketSize * n;
        n++;
    }
    for (var i = 0; i < values.length; i++) {
        // filter out values outside the min and max boundaries
        if (values[i] < min || values[i] > max) {
            continue;
        }
        var bound_1 = getBucketBound(values[i], bucketSize);
        histogram[bound_1] = histogram[bound_1] + 1;
    }
    var histogamSeries = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(histogram, function (count, bound) {
        return [Number(bound), count];
    });
    // Sort by Y axis values
    return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.sortBy(histogamSeries, function (point) { return point[0]; });
}
/**
 * Convert series into array of histogram data.
 * @param data Array of series
 * @param bucketSize
 */
function convertToHistogramData(data, bucketSize, hiddenSeries, min, max) {
    return data.map(function (series) {
        var values = getSeriesValues([series]);
        series.histogram = true;
        if (!hiddenSeries[series.alias]) {
            var histogram = convertValuesToHistogram(values, bucketSize, min, max);
            series.data = histogram;
        }
        else {
            series.data = [];
        }
        return series;
    });
}
function getBucketBound(value, bucketSize) {
    return Math.floor(value / bucketSize) * bucketSize;
}


/***/ }),

/***/ "./public/app/plugins/panel/graph/jquery.flot.events.ts":
/*!**************************************************************!*\
  !*** ./public/app/plugins/panel/graph/jquery.flot.events.ts ***!
  \**************************************************************/
/*! exports provided: createEditPopover, createAnnotationToolip, DrawableEvent, VisualEvent, EventMarkers, init */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createEditPopover", function() { return createEditPopover; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createAnnotationToolip", function() { return createAnnotationToolip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DrawableEvent", function() { return DrawableEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VisualEvent", function() { return VisualEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventMarkers", function() { return EventMarkers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "init", function() { return init; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tether-drop */ "./node_modules/tether-drop/dist/js/drop.js");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(tether_drop__WEBPACK_IMPORTED_MODULE_3__);



//@ts-ignore

/** @ngInject */
var createAnnotationToolip = function (element, event, plot) {
    var injector = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(document).injector();
    var content = document.createElement('div');
    content.innerHTML = '<annotation-tooltip event="event" on-edit="onEdit()"></annotation-tooltip>';
    injector.invoke([
        '$compile',
        '$rootScope',
        function ($compile, $rootScope) {
            var eventManager = plot.getOptions().events.manager;
            var tmpScope = $rootScope.$new(true);
            tmpScope.event = event;
            tmpScope.onEdit = function () {
                eventManager.editEvent(event);
            };
            $compile(content)(tmpScope);
            tmpScope.$digest();
            tmpScope.$destroy();
            var drop = new tether_drop__WEBPACK_IMPORTED_MODULE_3___default.a({
                target: element[0],
                content: content,
                position: 'bottom center',
                classes: 'drop-popover drop-popover--annotation',
                openOn: 'hover',
                hoverCloseDelay: 200,
                tetherOptions: {
                    constraints: [{ to: 'window', pin: true, attachment: 'both' }],
                },
            });
            drop.open();
            drop.on('close', function () {
                setTimeout(function () {
                    drop.destroy();
                });
            });
        },
    ]);
};
var markerElementToAttachTo = null;
/** @ngInject */
var createEditPopover = function (element, event, plot) {
    var eventManager = plot.getOptions().events.manager;
    if (eventManager.editorOpen) {
        // update marker element to attach to (needed in case of legend on the right
        // when there is a double render pass and the initial marker element is removed)
        markerElementToAttachTo = element;
        return;
    }
    // mark as openend
    eventManager.editorOpened();
    // set marker elment to attache to
    markerElementToAttachTo = element;
    // wait for element to be attached and positioned
    setTimeout(function () {
        var injector = angular__WEBPACK_IMPORTED_MODULE_0___default.a.element(document).injector();
        var content = document.createElement('div');
        content.innerHTML = '<event-editor panel-ctrl="panelCtrl" event="event" close="close()"></event-editor>';
        injector.invoke([
            '$compile',
            '$rootScope',
            function ($compile, $rootScope) {
                var scope = $rootScope.$new(true);
                var drop;
                scope.event = event;
                scope.panelCtrl = eventManager.panelCtrl;
                scope.close = function () {
                    drop.close();
                };
                $compile(content)(scope);
                scope.$digest();
                drop = new tether_drop__WEBPACK_IMPORTED_MODULE_3___default.a({
                    target: markerElementToAttachTo[0],
                    content: content,
                    position: 'bottom center',
                    classes: 'drop-popover drop-popover--form',
                    openOn: 'click',
                    tetherOptions: {
                        constraints: [{ to: 'window', pin: true, attachment: 'both' }],
                    },
                });
                drop.open();
                eventManager.editorOpened();
                drop.on('close', function () {
                    // need timeout here in order call drop.destroy
                    setTimeout(function () {
                        eventManager.editorClosed();
                        scope.$destroy();
                        drop.destroy();
                    });
                });
            },
        ]);
    }, 100);
};

/*
 * jquery.flot.events
 *
 * description: Flot plugin for adding events/markers to the plot
 * version: 0.2.5
 * authors:
 *    Alexander Wunschik <alex@wunschik.net>
 *    Joel Oughton <joeloughton@gmail.com>
 *    Nicolas Joseph <www.nicolasjoseph.com>
 *
 * website: https://github.com/mojoaxel/flot-events
 *
 * released under MIT License and GPLv2+
 */
/**
 * A class that allows for the drawing an remove of some object
 */
var DrawableEvent = /** @class */ (function () {
    /** @ngInject */
    function DrawableEvent(object, drawFunc, clearFunc, moveFunc, left, top, width, height) {
        this._object = object;
        this._drawFunc = drawFunc;
        this._clearFunc = clearFunc;
        this._moveFunc = moveFunc;
        this._position = { left: left, top: top };
        this._width = width;
        this._height = height;
    }
    DrawableEvent.prototype.width = function () {
        return this._width;
    };
    DrawableEvent.prototype.height = function () {
        return this._height;
    };
    DrawableEvent.prototype.position = function () {
        return this._position;
    };
    DrawableEvent.prototype.draw = function () {
        this._drawFunc(this._object);
    };
    DrawableEvent.prototype.clear = function () {
        this._clearFunc(this._object);
    };
    DrawableEvent.prototype.getObject = function () {
        return this._object;
    };
    DrawableEvent.prototype.moveTo = function (position) {
        this._position = position;
        this._moveFunc(this._object, this._position);
    };
    return DrawableEvent;
}());

/**
 * Event class that stores options (eventType, min, max, title, description) and the object to draw.
 */
var VisualEvent = /** @class */ (function () {
    /** @ngInject */
    function VisualEvent(options, drawableEvent) {
        this._options = options;
        this._drawableEvent = drawableEvent;
        this._hidden = false;
    }
    VisualEvent.prototype.visual = function () {
        return this._drawableEvent;
    };
    VisualEvent.prototype.getOptions = function () {
        return this._options;
    };
    VisualEvent.prototype.getParent = function () {
        return this._parent;
    };
    VisualEvent.prototype.isHidden = function () {
        return this._hidden;
    };
    VisualEvent.prototype.hide = function () {
        this._hidden = true;
    };
    VisualEvent.prototype.unhide = function () {
        this._hidden = false;
    };
    return VisualEvent;
}());

/**
 * A Class that handles the event-markers inside the given plot
 */
var EventMarkers = /** @class */ (function () {
    /** @ngInject */
    function EventMarkers(plot) {
        this._events = [];
        this._types = [];
        this._plot = plot;
        this.eventsEnabled = false;
    }
    EventMarkers.prototype.getEvents = function () {
        return this._events;
    };
    EventMarkers.prototype.setTypes = function (types) {
        return (this._types = types);
    };
    /**
     * create internal objects for the given events
     */
    EventMarkers.prototype.setupEvents = function (events) {
        var _this = this;
        var parts = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.partition(events, 'isRegion');
        var regions = parts[0];
        events = parts[1];
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(events, function (index, event) {
            var ve = new VisualEvent(event, _this._buildDiv(event));
            _this._events.push(ve);
        });
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(regions, function (index, event) {
            var vre = new VisualEvent(event, _this._buildRegDiv(event));
            _this._events.push(vre);
        });
        this._events.sort(function (a, b) {
            var ao = a.getOptions(), bo = b.getOptions();
            if (ao.min > bo.min) {
                return 1;
            }
            if (ao.min < bo.min) {
                return -1;
            }
            return 0;
        });
    };
    /**
     * draw the events to the plot
     */
    EventMarkers.prototype.drawEvents = function () {
        // var o = this._plot.getPlotOffset();
        var _this = this;
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(this._events, function (index, event) {
            // check event is inside the graph range
            if (_this._insidePlot(event.getOptions().min) && !event.isHidden()) {
                event.visual().draw();
            }
            else {
                event
                    .visual()
                    .getObject()
                    .hide();
            }
        });
    };
    /**
     * update the position of the event-markers (e.g. after scrolling or zooming)
     */
    EventMarkers.prototype.updateEvents = function () {
        var _this = this;
        var o = this._plot.getPlotOffset();
        var left;
        var top;
        var xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1];
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(this._events, function (index, event) {
            top = o.top + _this._plot.height() - event.visual().height();
            left = xaxis.p2c(event.getOptions().min) + o.left - event.visual().width() / 2;
            event.visual().moveTo({ top: top, left: left });
        });
    };
    /**
     * remove all events from the plot
     */
    EventMarkers.prototype._clearEvents = function () {
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(this._events, function (index, val) {
            val.visual().clear();
        });
        this._events = [];
    };
    /**
     * create a DOM element for the given event
     */
    EventMarkers.prototype._buildDiv = function (event) {
        var that = this;
        var container = this._plot.getPlaceholder();
        var o = this._plot.getPlotOffset();
        var xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1];
        var top, left, color, markerSize, markerShow, lineStyle, lineWidth;
        var markerTooltip;
        // map the eventType to a types object
        var eventTypeId = event.eventType;
        if (this._types === null || !this._types[eventTypeId] || !this._types[eventTypeId].color) {
            color = '#666';
        }
        else {
            color = this._types[eventTypeId].color;
        }
        if (this._types === null || !this._types[eventTypeId] || !this._types[eventTypeId].markerSize) {
            markerSize = 8; //default marker size
        }
        else {
            markerSize = this._types[eventTypeId].markerSize;
        }
        if (this._types === null || !this._types[eventTypeId] || this._types[eventTypeId].markerShow === undefined) {
            markerShow = true;
        }
        else {
            markerShow = this._types[eventTypeId].markerShow;
        }
        if (this._types === null || !this._types[eventTypeId] || this._types[eventTypeId].markerTooltip === undefined) {
            markerTooltip = true;
        }
        else {
            markerTooltip = this._types[eventTypeId].markerTooltip;
        }
        if (this._types == null || !this._types[eventTypeId] || !this._types[eventTypeId].lineStyle) {
            lineStyle = 'dashed'; //default line style
        }
        else {
            lineStyle = this._types[eventTypeId].lineStyle.toLowerCase();
        }
        if (this._types == null || !this._types[eventTypeId] || this._types[eventTypeId].lineWidth === undefined) {
            lineWidth = 1; //default line width
        }
        else {
            lineWidth = this._types[eventTypeId].lineWidth;
        }
        var topOffset = xaxis.options.eventSectionHeight || 0;
        topOffset = topOffset / 3;
        top = o.top + this._plot.height() + topOffset;
        left = xaxis.p2c(event.min) + o.left;
        var line = jquery__WEBPACK_IMPORTED_MODULE_1___default()('<div class="events_line flot-temp-elem"></div>')
            .css({
            position: 'absolute',
            opacity: 0.8,
            left: left + 'px',
            top: 8,
            width: lineWidth + 'px',
            height: this._plot.height() + topOffset * 0.8,
            'border-left-width': lineWidth + 'px',
            'border-left-style': lineStyle,
            'border-left-color': color,
            color: color,
        })
            .appendTo(container);
        if (markerShow) {
            var marker_1 = jquery__WEBPACK_IMPORTED_MODULE_1___default()('<div class="events_marker"></div>').css({
                position: 'absolute',
                left: -markerSize - Math.round(lineWidth / 2) + 'px',
                'font-size': 0,
                'line-height': 0,
                width: 0,
                height: 0,
                'border-left': markerSize + 'px solid transparent',
                'border-right': markerSize + 'px solid transparent',
            });
            marker_1.appendTo(line);
            if (this._types[eventTypeId] &&
                this._types[eventTypeId].position &&
                this._types[eventTypeId].position.toUpperCase() === 'BOTTOM') {
                marker_1.css({
                    top: top - markerSize - 8 + 'px',
                    'border-top': 'none',
                    'border-bottom': markerSize + 'px solid ' + color,
                });
            }
            else {
                marker_1.css({
                    top: '0px',
                    'border-top': markerSize + 'px solid ' + color,
                    'border-bottom': 'none',
                });
            }
            marker_1.data({
                event: event,
            });
            var mouseenter = function () {
                createAnnotationToolip(marker_1, jquery__WEBPACK_IMPORTED_MODULE_1___default()(this).data('event'), that._plot);
            };
            if (event.editModel) {
                createEditPopover(marker_1, event.editModel, that._plot);
            }
            var mouseleave = function () {
                that._plot.clearSelection();
            };
            if (markerTooltip) {
                marker_1.css({ cursor: 'help' });
                marker_1.hover(mouseenter, mouseleave);
            }
        }
        var drawableEvent = new DrawableEvent(line, function drawFunc(obj) {
            obj.show();
        }, function (obj) {
            obj.remove();
        }, function (obj, position) {
            obj.css({
                top: position.top,
                left: position.left,
            });
        }, left, top, line.width(), line.height());
        return drawableEvent;
    };
    /**
     * create a DOM element for the given region
     */
    EventMarkers.prototype._buildRegDiv = function (event) {
        var _this = this;
        var that = this;
        var container = this._plot.getPlaceholder();
        var o = this._plot.getPlotOffset();
        var xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1];
        var top, left, lineWidth, regionWidth, lineStyle, color, markerTooltip;
        // map the eventType to a types object
        var eventTypeId = event.eventType;
        if (this._types === null || !this._types[eventTypeId] || !this._types[eventTypeId].color) {
            color = '#666';
        }
        else {
            color = this._types[eventTypeId].color;
        }
        if (this._types === null || !this._types[eventTypeId] || this._types[eventTypeId].markerTooltip === undefined) {
            markerTooltip = true;
        }
        else {
            markerTooltip = this._types[eventTypeId].markerTooltip;
        }
        if (this._types == null || !this._types[eventTypeId] || this._types[eventTypeId].lineWidth === undefined) {
            lineWidth = 1; //default line width
        }
        else {
            lineWidth = this._types[eventTypeId].lineWidth;
        }
        if (this._types == null || !this._types[eventTypeId] || !this._types[eventTypeId].lineStyle) {
            lineStyle = 'dashed'; //default line style
        }
        else {
            lineStyle = this._types[eventTypeId].lineStyle.toLowerCase();
        }
        var topOffset = 2;
        top = o.top + this._plot.height() + topOffset;
        var timeFrom = Math.min(event.min, event.timeEnd);
        var timeTo = Math.max(event.min, event.timeEnd);
        left = xaxis.p2c(timeFrom) + o.left;
        var right = xaxis.p2c(timeTo) + o.left;
        regionWidth = right - left;
        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.each([left, right], function (position) {
            var line = jquery__WEBPACK_IMPORTED_MODULE_1___default()('<div class="events_line flot-temp-elem"></div>').css({
                position: 'absolute',
                opacity: 0.8,
                left: position + 'px',
                top: 8,
                width: lineWidth + 'px',
                height: _this._plot.height() + topOffset,
                'border-left-width': lineWidth + 'px',
                'border-left-style': lineStyle,
                'border-left-color': color,
                color: color,
            });
            line.appendTo(container);
        });
        var region = jquery__WEBPACK_IMPORTED_MODULE_1___default()('<div class="events_marker region_marker flot-temp-elem"></div>').css({
            position: 'absolute',
            opacity: 0.5,
            left: left + 'px',
            top: top,
            width: Math.round(regionWidth + lineWidth) + 'px',
            height: '0.5rem',
            'border-left-color': color,
            color: color,
            'background-color': color,
        });
        region.appendTo(container);
        region.data({
            event: event,
        });
        var mouseenter = function () {
            createAnnotationToolip(region, jquery__WEBPACK_IMPORTED_MODULE_1___default()(this).data('event'), that._plot);
        };
        if (event.editModel) {
            createEditPopover(region, event.editModel, that._plot);
        }
        var mouseleave = function () {
            that._plot.clearSelection();
        };
        if (markerTooltip) {
            region.css({ cursor: 'help' });
            region.hover(mouseenter, mouseleave);
        }
        var drawableEvent = new DrawableEvent(region, function drawFunc(obj) {
            obj.show();
        }, function (obj) {
            obj.remove();
        }, function (obj, position) {
            obj.css({
                top: position.top,
                left: position.left,
            });
        }, left, top, region.width(), region.height());
        return drawableEvent;
    };
    /**
     * check if the event is inside visible range
     */
    EventMarkers.prototype._insidePlot = function (x) {
        var xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1];
        var xc = xaxis.p2c(x);
        return xc > 0 && xc < xaxis.p2c(xaxis.max);
    };
    return EventMarkers;
}());

/**
 * initialize the plugin for the given plot
 */
/** @ngInject */
function init(plot) {
    /*jshint validthis:true */
    var that = this;
    var eventMarkers = new EventMarkers(plot);
    plot.getEvents = function () {
        return eventMarkers._events;
    };
    plot.hideEvents = function () {
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(eventMarkers._events, function (index, event) {
            event
                .visual()
                .getObject()
                .hide();
        });
    };
    plot.showEvents = function () {
        plot.hideEvents();
        jquery__WEBPACK_IMPORTED_MODULE_1___default.a.each(eventMarkers._events, function (index, event) {
            event.hide();
        });
        that.eventMarkers.drawEvents();
    };
    // change events on an existing plot
    plot.setEvents = function (events) {
        if (eventMarkers.eventsEnabled) {
            eventMarkers.setupEvents(events);
        }
    };
    plot.hooks.processOptions.push(function (plot, options) {
        // enable the plugin
        if (options.events.data != null) {
            eventMarkers.eventsEnabled = true;
        }
    });
    plot.hooks.draw.push(function (plot) {
        var options = plot.getOptions();
        if (eventMarkers.eventsEnabled) {
            // check for first run
            if (eventMarkers.getEvents().length < 1) {
                eventMarkers.setTypes(options.events.types);
                eventMarkers.setupEvents(options.events.data);
            }
            else {
                eventMarkers.updateEvents();
            }
        }
        eventMarkers.drawEvents();
    });
}
var defaultOptions = {
    events: {
        data: null,
        types: null,
        xaxis: 1,
        position: 'BOTTOM',
    },
};
jquery__WEBPACK_IMPORTED_MODULE_1___default.a.plot.plugins.push({
    init: init,
    options: defaultOptions,
    name: 'events',
    version: '0.2.5',
});


/***/ }),

/***/ "./public/app/plugins/panel/graph/module.ts":
/*!**************************************************!*\
  !*** ./public/app/plugins/panel/graph/module.ts ***!
  \**************************************************/
/*! exports provided: GraphCtrl, PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphCtrl", function() { return GraphCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return GraphCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _graph__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./graph */ "./public/app/plugins/panel/graph/graph.ts");
/* harmony import */ var _series_overrides_ctrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./series_overrides_ctrl */ "./public/app/plugins/panel/graph/series_overrides_ctrl.ts");
/* harmony import */ var _thresholds_form__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./thresholds_form */ "./public/app/plugins/panel/graph/thresholds_form.ts");
/* harmony import */ var _time_regions_form__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./time_regions_form */ "./public/app/plugins/panel/graph/time_regions_form.ts");
/* harmony import */ var _template__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./template */ "./public/app/plugins/panel/graph/template.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var _data_processor__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./data_processor */ "./public/app/plugins/panel/graph/data_processor.ts");
/* harmony import */ var _axes_editor__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./axes_editor */ "./public/app/plugins/panel/graph/axes_editor.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_dashboard_state_runRequest__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/features/dashboard/state/runRequest */ "./public/app/features/dashboard/state/runRequest.ts");
/* harmony import */ var _GraphContextMenuCtrl__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./GraphContextMenuCtrl */ "./public/app/plugins/panel/graph/GraphContextMenuCtrl.ts");
/* harmony import */ var app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! app/features/panel/panellinks/link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");















var GraphCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GraphCtrl, _super);
    /** @ngInject */
    function GraphCtrl($scope, $injector, annotationsSrv) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.annotationsSrv = annotationsSrv;
        _this.hiddenSeries = {};
        _this.seriesList = [];
        _this.dataList = [];
        _this.annotations = [];
        _this.colors = [];
        _this.linkVariableSuggestions = [];
        _this.panelDefaults = {
            // datasource name, null = default datasource
            datasource: null,
            // sets client side (flot) or native graphite png renderer (png)
            renderer: 'flot',
            yaxes: [
                {
                    label: null,
                    show: true,
                    logBase: 1,
                    min: null,
                    max: null,
                    format: 'short',
                },
                {
                    label: null,
                    show: true,
                    logBase: 1,
                    min: null,
                    max: null,
                    format: 'short',
                },
            ],
            xaxis: {
                show: true,
                mode: 'time',
                name: null,
                values: [],
                buckets: null,
            },
            yaxis: {
                align: false,
                alignLevel: null,
            },
            // show/hide lines
            lines: true,
            // fill factor
            fill: 1,
            // fill factor
            fillGradient: 0,
            // line width in pixels
            linewidth: 1,
            // show/hide dashed line
            dashes: false,
            // length of a dash
            dashLength: 10,
            // length of space between two dashes
            spaceLength: 10,
            // show hide points
            points: false,
            // point radius in pixels
            pointradius: 2,
            // show hide bars
            bars: false,
            // enable/disable stacking
            stack: false,
            // stack percentage mode
            percentage: false,
            // legend options
            legend: {
                show: true,
                values: false,
                min: false,
                max: false,
                current: false,
                total: false,
                avg: false,
            },
            // how null points should be handled
            nullPointMode: 'null',
            // staircase line mode
            steppedLine: false,
            // tooltip options
            tooltip: {
                value_type: 'individual',
                shared: true,
                sort: 0,
            },
            // time overrides
            timeFrom: null,
            timeShift: null,
            // metric queries
            targets: [{}],
            // series color overrides
            aliasColors: {},
            // other style overrides
            seriesOverrides: [],
            thresholds: [],
            timeRegions: [],
            options: {
                dataLinks: [],
            },
        };
        _this.onColorChange = function (series, color) {
            series.setColor(Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_11__["getColorFromHexRgbOrName"])(color, app_core_config__WEBPACK_IMPORTED_MODULE_10__["default"].theme.type));
            _this.panel.aliasColors[series.alias] = color;
            _this.render();
        };
        _this.onToggleSeries = function (hiddenSeries) {
            _this.hiddenSeries = hiddenSeries;
            _this.render();
        };
        _this.onToggleSort = function (sortBy, sortDesc) {
            _this.panel.legend.sort = sortBy;
            _this.panel.legend.sortDesc = sortDesc;
            _this.render();
        };
        _this.onToggleAxis = function (info) {
            var override = lodash__WEBPACK_IMPORTED_MODULE_6___default.a.find(_this.panel.seriesOverrides, { alias: info.alias });
            if (!override) {
                override = { alias: info.alias };
                _this.panel.seriesOverrides.push(override);
            }
            override.yaxis = info.yaxis;
            _this.render();
        };
        _this.onContextMenuClose = function () {
            _this.contextMenuCtrl.toggleMenu();
        };
        _this.formatDate = function (date, format) {
            return _this.dashboard.formatDate.apply(_this.dashboard, [date, format]);
        };
        _this.getDataFrameByRefId = function (refId) {
            return _this.dataList.filter(function (dataFrame) { return dataFrame.refId === refId; })[0];
        };
        lodash__WEBPACK_IMPORTED_MODULE_6___default.a.defaults(_this.panel, _this.panelDefaults);
        lodash__WEBPACK_IMPORTED_MODULE_6___default.a.defaults(_this.panel.tooltip, _this.panelDefaults.tooltip);
        lodash__WEBPACK_IMPORTED_MODULE_6___default.a.defaults(_this.panel.legend, _this.panelDefaults.legend);
        lodash__WEBPACK_IMPORTED_MODULE_6___default.a.defaults(_this.panel.xaxis, _this.panelDefaults.xaxis);
        lodash__WEBPACK_IMPORTED_MODULE_6___default.a.defaults(_this.panel.options, _this.panelDefaults.options);
        _this.useDataFrames = true;
        _this.processor = new _data_processor__WEBPACK_IMPORTED_MODULE_8__["DataProcessor"](_this.panel);
        _this.contextMenuCtrl = new _GraphContextMenuCtrl__WEBPACK_IMPORTED_MODULE_13__["GraphContextMenuCtrl"]($scope);
        _this.events.on('render', _this.onRender.bind(_this));
        _this.events.on('data-frames-received', _this.onDataFramesReceived.bind(_this));
        _this.events.on('data-error', _this.onDataError.bind(_this));
        _this.events.on('data-snapshot-load', _this.onDataSnapshotLoad.bind(_this));
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.events.on('init-panel-actions', _this.onInitPanelActions.bind(_this));
        _this.onDataLinksChange = _this.onDataLinksChange.bind(_this);
        return _this;
    }
    GraphCtrl.prototype.onInitEditMode = function () {
        this.addEditorTab('Display options', 'public/app/plugins/panel/graph/tab_display.html');
        this.addEditorTab('Axes', _axes_editor__WEBPACK_IMPORTED_MODULE_9__["axesEditorComponent"]);
        this.addEditorTab('Legend', 'public/app/plugins/panel/graph/tab_legend.html');
        this.addEditorTab('Thresholds & Time Regions', 'public/app/plugins/panel/graph/tab_thresholds_time_regions.html');
        this.addEditorTab('Data links', 'public/app/plugins/panel/graph/tab_drilldown_links.html');
        this.subTabIndex = 0;
    };
    GraphCtrl.prototype.onInitPanelActions = function (actions) {
        actions.push({ text: 'Export CSV', click: 'ctrl.exportCsv()' });
        actions.push({ text: 'Toggle legend', click: 'ctrl.toggleLegend()', shortcut: 'p l' });
    };
    GraphCtrl.prototype.issueQueries = function (datasource) {
        var _this = this;
        this.annotationsPromise = this.annotationsSrv.getAnnotations({
            dashboard: this.dashboard,
            panel: this.panel,
            range: this.range,
        });
        /* Wait for annotationSrv requests to get datasources to
         * resolve before issuing queries. This allows the annotations
         * service to fire annotations queries before graph queries
         * (but not wait for completion). This resolves
         * issue 11806.
         */
        return this.annotationsSrv.datasourcePromises.then(function (r) {
            return _super.prototype.issueQueries.call(_this, datasource);
        });
    };
    GraphCtrl.prototype.zoomOut = function (evt) {
        this.publishAppEvent('zoom-out', 2);
    };
    GraphCtrl.prototype.onDataSnapshotLoad = function (snapshotData) {
        this.annotationsPromise = this.annotationsSrv.getAnnotations({
            dashboard: this.dashboard,
            panel: this.panel,
            range: this.range,
        });
        var frames = Object(app_features_dashboard_state_runRequest__WEBPACK_IMPORTED_MODULE_12__["getProcessedDataFrames"])(snapshotData);
        this.onDataFramesReceived(frames);
    };
    GraphCtrl.prototype.onDataError = function (err) {
        this.seriesList = [];
        this.annotations = [];
        this.render([]);
    };
    GraphCtrl.prototype.onDataFramesReceived = function (data) {
        var e_1, _a;
        var _this = this;
        this.dataList = data;
        this.seriesList = this.processor.getSeriesList({
            dataList: this.dataList,
            range: this.range,
        });
        this.linkVariableSuggestions = Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_14__["getDataLinksVariableSuggestions"])(data);
        this.dataWarning = null;
        var datapointsCount = this.seriesList.reduce(function (prev, series) {
            return prev + series.datapoints.length;
        }, 0);
        if (datapointsCount === 0) {
            this.dataWarning = {
                title: 'No data',
                tip: 'No data returned from query',
            };
        }
        else {
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.seriesList), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var series = _c.value;
                    if (series.isOutsideRange) {
                        this.dataWarning = {
                            title: 'Data outside time range',
                            tip: 'Can be caused by timezone mismatch or missing time filter in query',
                        };
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
        this.annotationsPromise.then(function (result) {
            _this.loading = false;
            _this.alertState = result.alertState;
            _this.annotations = result.annotations;
            _this.render(_this.seriesList);
        }, function () {
            _this.loading = false;
            _this.render(_this.seriesList);
        });
    };
    GraphCtrl.prototype.onRender = function () {
        var e_2, _a;
        if (!this.seriesList) {
            return;
        }
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.seriesList), _c = _b.next(); !_c.done; _c = _b.next()) {
                var series = _c.value;
                series.applySeriesOverrides(this.panel.seriesOverrides);
                if (series.unit) {
                    this.panel.yaxes[series.yaxis - 1].format = series.unit;
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
    };
    GraphCtrl.prototype.onDataLinksChange = function (dataLinks) {
        this.panel.updateOptions(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this.panel.options, { dataLinks: dataLinks }));
    };
    GraphCtrl.prototype.addSeriesOverride = function (override) {
        this.panel.seriesOverrides.push(override || {});
    };
    GraphCtrl.prototype.removeSeriesOverride = function (override) {
        this.panel.seriesOverrides = lodash__WEBPACK_IMPORTED_MODULE_6___default.a.without(this.panel.seriesOverrides, override);
        this.render();
    };
    GraphCtrl.prototype.toggleLegend = function () {
        this.panel.legend.show = !this.panel.legend.show;
        this.render();
    };
    GraphCtrl.prototype.legendValuesOptionChanged = function () {
        var legend = this.panel.legend;
        legend.values = legend.min || legend.max || legend.avg || legend.current || legend.total;
        this.render();
    };
    GraphCtrl.prototype.exportCsv = function () {
        var scope = this.$scope.$new(true);
        scope.seriesList = this.seriesList;
        this.publishAppEvent('show-modal', {
            templateHtml: '<export-data-modal data="seriesList"></export-data-modal>',
            scope: scope,
            modalClass: 'modal--narrow',
        });
    };
    GraphCtrl.template = _template__WEBPACK_IMPORTED_MODULE_5__["default"];
    return GraphCtrl;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_7__["MetricsPanelCtrl"]));



/***/ }),

/***/ "./public/app/plugins/panel/graph/series_overrides_ctrl.ts":
/*!*****************************************************************!*\
  !*** ./public/app/plugins/panel/graph/series_overrides_ctrl.ts ***!
  \*****************************************************************/
/*! exports provided: SeriesOverridesCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SeriesOverridesCtrl", function() { return SeriesOverridesCtrl; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");


/** @ngInject */
function SeriesOverridesCtrl($scope, $element, popoverSrv) {
    $scope.overrideMenu = [];
    $scope.currentOverrides = [];
    $scope.override = $scope.override || {};
    $scope.colorPickerModel = {};
    $scope.addOverrideOption = function (name, propertyName, values) {
        var option = {
            text: name,
            propertyName: propertyName,
            index: $scope.overrideMenu.length,
            values: values,
            submenu: lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(values, function (value) {
                return { text: String(value), value: value };
            }),
        };
        $scope.overrideMenu.push(option);
    };
    $scope.setOverride = function (item, subItem) {
        // handle color overrides
        if (item.propertyName === 'color') {
            $scope.openColorSelector($scope.override['color']);
            return;
        }
        $scope.override[item.propertyName] = subItem.value;
        // automatically disable lines for this series and the fill below to series
        // can be removed by the user if they still want lines
        if (item.propertyName === 'fillBelowTo') {
            $scope.override['lines'] = false;
            $scope.ctrl.addSeriesOverride({ alias: subItem.value, lines: false });
        }
        $scope.updateCurrentOverrides();
        $scope.ctrl.render();
    };
    $scope.colorSelected = function (color) {
        $scope.override['color'] = color;
        $scope.updateCurrentOverrides();
        $scope.ctrl.render();
        // update picker model so that the picker UI will also update
        $scope.colorPickerModel.series.color = color;
    };
    $scope.openColorSelector = function (color) {
        $scope.colorPickerModel = {
            autoClose: true,
            colorSelected: $scope.colorSelected,
            series: { color: color },
        };
        popoverSrv.show({
            element: $element.find('.dropdown')[0],
            position: 'top center',
            openOn: 'click',
            template: '<series-color-picker-popover color="series.color" onColorChange="colorSelected" />',
            classNames: 'drop-popover drop-popover--transparent',
            model: $scope.colorPickerModel,
            onClose: function () {
                $scope.ctrl.render();
            },
        });
    };
    $scope.removeOverride = function (option) {
        delete $scope.override[option.propertyName];
        $scope.updateCurrentOverrides();
        $scope.ctrl.refresh();
    };
    $scope.getSeriesNames = function () {
        return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map($scope.ctrl.seriesList, function (series) {
            return series.alias;
        });
    };
    $scope.updateCurrentOverrides = function () {
        $scope.currentOverrides = [];
        lodash__WEBPACK_IMPORTED_MODULE_0___default.a.each($scope.overrideMenu, function (option) {
            var value = $scope.override[option.propertyName];
            if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isUndefined(value)) {
                return;
            }
            $scope.currentOverrides.push({
                name: option.text,
                propertyName: option.propertyName,
                value: String(value),
            });
        });
    };
    $scope.addOverrideOption('Bars', 'bars', [true, false]);
    $scope.addOverrideOption('Lines', 'lines', [true, false]);
    $scope.addOverrideOption('Line fill', 'fill', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    $scope.addOverrideOption('Line width', 'linewidth', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    $scope.addOverrideOption('Null point mode', 'nullPointMode', ['connected', 'null', 'null as zero']);
    $scope.addOverrideOption('Fill below to', 'fillBelowTo', $scope.getSeriesNames());
    $scope.addOverrideOption('Staircase line', 'steppedLine', [true, false]);
    $scope.addOverrideOption('Dashes', 'dashes', [true, false]);
    $scope.addOverrideOption('Dash Length', 'dashLength', [
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
    ]);
    $scope.addOverrideOption('Dash Space', 'spaceLength', [
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
    ]);
    $scope.addOverrideOption('Points', 'points', [true, false]);
    $scope.addOverrideOption('Points Radius', 'pointradius', [1, 2, 3, 4, 5]);
    $scope.addOverrideOption('Stack', 'stack', [true, false, 'A', 'B', 'C', 'D']);
    $scope.addOverrideOption('Color', 'color', ['change']);
    $scope.addOverrideOption('Y-axis', 'yaxis', [1, 2]);
    $scope.addOverrideOption('Z-index', 'zindex', [-3, -2, -1, 0, 1, 2, 3]);
    $scope.addOverrideOption('Transform', 'transform', ['constant', 'negative-Y']);
    $scope.addOverrideOption('Legend', 'legend', [true, false]);
    $scope.addOverrideOption('Hide in tooltip', 'hideTooltip', [true, false]);
    $scope.updateCurrentOverrides();
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_1__["default"].controller('SeriesOverridesCtrl', SeriesOverridesCtrl);


/***/ }),

/***/ "./public/app/plugins/panel/graph/template.ts":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/graph/template.ts ***!
  \****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var template = "\n<div class=\"graph-panel\" ng-class=\"{'graph-panel--legend-right': ctrl.panel.legend.rightSide}\">\n  <div class=\"graph-panel__chart\" grafana-graph ng-dblclick=\"ctrl.zoomOut()\">\n  </div>\n\n  <div class=\"graph-legend\">\n    <div class=\"graph-legend-content\" graph-legend></div>\n  </div>\n  <div ng-if=\"ctrl.contextMenuCtrl.isVisible\">\n    <graph-context-menu\n      items=\"ctrl.contextMenuCtrl.menuItemsSupplier()\"\n      onClose=\"ctrl.onContextMenuClose\"\n      getContextMenuSource=\"ctrl.contextMenuCtrl.getSource\"\n      formatSourceDate=\"ctrl.formatDate\"\n      x=\"ctrl.contextMenuCtrl.position.x\"\n      y=\"ctrl.contextMenuCtrl.position.y\"\n    ></graph-context-menu>\n  </div>\n</div>\n";
/* harmony default export */ __webpack_exports__["default"] = (template);


/***/ }),

/***/ "./public/app/plugins/panel/graph/threshold_manager.ts":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/graph/threshold_manager.ts ***!
  \*************************************************************/
/*! exports provided: ThresholdManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThresholdManager", function() { return ThresholdManager; });
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vendor/flot/jquery.flot */ "./public/vendor/flot/jquery.flot.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");




var ThresholdManager = /** @class */ (function () {
    function ThresholdManager(panelCtrl) {
        this.panelCtrl = panelCtrl;
    }
    ThresholdManager.prototype.getHandleHtml = function (handleIndex, model, valueStr) {
        var stateClass = model.colorMode;
        if (model.colorMode === 'custom') {
            stateClass = 'critical';
        }
        return "\n    <div class=\"alert-handle-wrapper alert-handle-wrapper--T" + handleIndex + "\">\n      <div class=\"alert-handle-line alert-handle-line--" + stateClass + "\">\n      </div>\n      <div class=\"alert-handle\" data-handle-index=\"" + handleIndex + "\">\n        <i class=\"icon-gf icon-gf-" + stateClass + " alert-state-" + stateClass + "\"></i>\n        <span class=\"alert-handle-value\">" + valueStr + "<i class=\"alert-handle-grip\"></i></span>\n      </div>\n    </div>";
    };
    ThresholdManager.prototype.initDragging = function (evt) {
        var handleElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(evt.currentTarget).parents('.alert-handle-wrapper');
        var handleIndex = jquery__WEBPACK_IMPORTED_MODULE_1___default()(evt.currentTarget).data('handleIndex');
        var lastY = null;
        var posTop;
        var plot = this.plot;
        var panelCtrl = this.panelCtrl;
        var model = this.thresholds[handleIndex];
        function dragging(evt) {
            if (lastY === null) {
                lastY = evt.clientY;
            }
            else {
                var diff = evt.clientY - lastY;
                posTop = posTop + diff;
                lastY = evt.clientY;
                handleElem.css({ top: posTop + diff });
            }
        }
        function stopped() {
            // calculate graph level
            var graphValue = plot.c2p({ left: 0, top: posTop }).y;
            graphValue = parseInt(graphValue.toFixed(0), 10);
            model.value = graphValue;
            handleElem.off('mousemove', dragging);
            handleElem.off('mouseup', dragging);
            handleElem.off('mouseleave', dragging);
            // trigger digest and render
            panelCtrl.$scope.$apply(function () {
                panelCtrl.render();
                panelCtrl.events.emit('threshold-changed', {
                    threshold: model,
                    handleIndex: handleIndex,
                });
            });
        }
        lastY = null;
        posTop = handleElem.position().top;
        handleElem.on('mousemove', dragging);
        handleElem.on('mouseup', stopped);
        handleElem.on('mouseleave', stopped);
    };
    ThresholdManager.prototype.cleanUp = function () {
        this.placeholder.find('.alert-handle-wrapper').remove();
        this.needsCleanup = false;
    };
    ThresholdManager.prototype.renderHandle = function (handleIndex, defaultHandleTopPos) {
        var model = this.thresholds[handleIndex];
        var value = model.value;
        var valueStr = value;
        var handleTopPos = 0;
        // handle no value
        if (!lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNumber(value)) {
            valueStr = '';
            handleTopPos = defaultHandleTopPos;
        }
        else {
            var valueCanvasPos = this.plot.p2c({ x: 0, y: value });
            handleTopPos = Math.round(Math.min(Math.max(valueCanvasPos.top, 0), this.height) - 6);
        }
        var handleElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(this.getHandleHtml(handleIndex, model, valueStr));
        this.placeholder.append(handleElem);
        handleElem.toggleClass('alert-handle-wrapper--no-value', valueStr === '');
        handleElem.css({ top: handleTopPos });
    };
    ThresholdManager.prototype.shouldDrawHandles = function () {
        // @ts-ignore
        return !this.hasSecondYAxis && this.panelCtrl.editingThresholds && this.panelCtrl.panel.thresholds.length > 0;
    };
    ThresholdManager.prototype.prepare = function (elem, data) {
        this.hasSecondYAxis = false;
        for (var i = 0; i < data.length; i++) {
            if (data[i].yaxis > 1) {
                this.hasSecondYAxis = true;
                break;
            }
        }
        if (this.shouldDrawHandles()) {
            var thresholdMargin = this.panelCtrl.panel.thresholds.length > 1 ? '220px' : '110px';
            elem.css('margin-right', thresholdMargin);
        }
        else if (this.needsCleanup) {
            elem.css('margin-right', '0');
        }
    };
    ThresholdManager.prototype.draw = function (plot) {
        this.thresholds = this.panelCtrl.panel.thresholds;
        this.plot = plot;
        this.placeholder = plot.getPlaceholder();
        if (this.needsCleanup) {
            this.cleanUp();
        }
        if (!this.shouldDrawHandles()) {
            return;
        }
        this.height = plot.height();
        if (this.thresholds.length > 0) {
            this.renderHandle(0, 10);
        }
        if (this.thresholds.length > 1) {
            this.renderHandle(1, this.height - 30);
        }
        this.placeholder.off('mousedown', '.alert-handle');
        this.placeholder.on('mousedown', '.alert-handle', this.initDragging.bind(this));
        this.needsCleanup = true;
    };
    ThresholdManager.prototype.addFlotOptions = function (options, panel) {
        if (!panel.thresholds || panel.thresholds.length === 0) {
            return;
        }
        var gtLimit = Infinity;
        var ltLimit = -Infinity;
        var i, threshold, other;
        for (i = 0; i < panel.thresholds.length; i++) {
            threshold = panel.thresholds[i];
            if (!lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNumber(threshold.value)) {
                continue;
            }
            var limit = void 0;
            switch (threshold.op) {
                case 'gt': {
                    limit = gtLimit;
                    // if next threshold is less then op and greater value, then use that as limit
                    if (panel.thresholds.length > i + 1) {
                        other = panel.thresholds[i + 1];
                        if (other.value > threshold.value) {
                            limit = other.value;
                            ltLimit = limit;
                        }
                    }
                    break;
                }
                case 'lt': {
                    limit = ltLimit;
                    // if next threshold is less then op and greater value, then use that as limit
                    if (panel.thresholds.length > i + 1) {
                        other = panel.thresholds[i + 1];
                        if (other.value < threshold.value) {
                            limit = other.value;
                            gtLimit = limit;
                        }
                    }
                    break;
                }
            }
            var fillColor = void 0, lineColor = void 0;
            switch (threshold.colorMode) {
                case 'critical': {
                    fillColor = 'rgba(234, 112, 112, 0.12)';
                    lineColor = 'rgba(237, 46, 24, 0.60)';
                    break;
                }
                case 'warning': {
                    fillColor = 'rgba(235, 138, 14, 0.12)';
                    lineColor = 'rgba(247, 149, 32, 0.60)';
                    break;
                }
                case 'ok': {
                    fillColor = 'rgba(11, 237, 50, 0.090)';
                    lineColor = 'rgba(6,163,69, 0.60)';
                    break;
                }
                case 'custom': {
                    fillColor = threshold.fillColor;
                    lineColor = threshold.lineColor;
                    break;
                }
            }
            // fill
            if (threshold.fill) {
                if (threshold.yaxis === 'right' && this.hasSecondYAxis) {
                    options.grid.markings.push({
                        y2axis: { from: threshold.value, to: limit },
                        color: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(fillColor),
                    });
                }
                else {
                    options.grid.markings.push({
                        yaxis: { from: threshold.value, to: limit },
                        color: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(fillColor),
                    });
                }
            }
            if (threshold.line) {
                if (threshold.yaxis === 'right' && this.hasSecondYAxis) {
                    options.grid.markings.push({
                        y2axis: { from: threshold.value, to: threshold.value },
                        color: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(lineColor),
                    });
                }
                else {
                    options.grid.markings.push({
                        yaxis: { from: threshold.value, to: threshold.value },
                        color: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(lineColor),
                    });
                }
            }
        }
    };
    return ThresholdManager;
}());



/***/ }),

/***/ "./public/app/plugins/panel/graph/thresholds_form.ts":
/*!***********************************************************!*\
  !*** ./public/app/plugins/panel/graph/thresholds_form.ts ***!
  \***********************************************************/
/*! exports provided: ThresholdFormCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThresholdFormCtrl", function() { return ThresholdFormCtrl; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tinycolor2 */ "./node_modules/tinycolor2/tinycolor.js");
/* harmony import */ var tinycolor2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(tinycolor2__WEBPACK_IMPORTED_MODULE_2__);



var ThresholdFormCtrl = /** @class */ (function () {
    /** @ngInject */
    function ThresholdFormCtrl($scope) {
        var _this = this;
        this.panel = this.panelCtrl.panel;
        if (this.panel.alert) {
            this.disabled = true;
        }
        var unbindDestroy = $scope.$on('$destroy', function () {
            _this.panelCtrl.editingThresholds = false;
            _this.panelCtrl.render();
            unbindDestroy();
        });
        this.panelCtrl.editingThresholds = true;
    }
    ThresholdFormCtrl.prototype.addThreshold = function () {
        this.panel.thresholds.push({
            value: undefined,
            colorMode: 'critical',
            op: 'gt',
            fill: true,
            line: true,
            yaxis: 'left',
        });
        this.panelCtrl.render();
    };
    ThresholdFormCtrl.prototype.removeThreshold = function (index) {
        this.panel.thresholds.splice(index, 1);
        this.panelCtrl.render();
    };
    ThresholdFormCtrl.prototype.render = function () {
        this.panelCtrl.render();
    };
    ThresholdFormCtrl.prototype.onFillColorChange = function (index) {
        var _this = this;
        return function (newColor) {
            _this.panel.thresholds[index].fillColor = newColor;
            _this.render();
        };
    };
    ThresholdFormCtrl.prototype.onLineColorChange = function (index) {
        var _this = this;
        return function (newColor) {
            _this.panel.thresholds[index].lineColor = newColor;
            _this.render();
        };
    };
    ThresholdFormCtrl.prototype.onThresholdTypeChange = function (index) {
        // Because of the ng-model binding, threshold's color mode is already set here
        if (this.panel.thresholds[index].colorMode === 'custom') {
            this.panel.thresholds[index].fillColor = tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].theme.colors.blueBase)
                .setAlpha(0.2)
                .toRgbString();
            this.panel.thresholds[index].lineColor = tinycolor2__WEBPACK_IMPORTED_MODULE_2___default()(app_core_config__WEBPACK_IMPORTED_MODULE_1__["default"].theme.colors.blueShade)
                .setAlpha(0.6)
                .toRgbString();
        }
        this.panelCtrl.render();
    };
    return ThresholdFormCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('graphThresholdForm', function () {
    return {
        restrict: 'E',
        templateUrl: 'public/app/plugins/panel/graph/thresholds_form.html',
        controller: ThresholdFormCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            panelCtrl: '=',
        },
    };
});


/***/ }),

/***/ "./public/app/plugins/panel/graph/time_region_manager.ts":
/*!***************************************************************!*\
  !*** ./public/app/plugins/panel/graph/time_region_manager.ts ***!
  \***************************************************************/
/*! exports provided: colorModes, getColorModes, TimeRegionManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorModes", function() { return colorModes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorModes", function() { return getColorModes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeRegionManager", function() { return TimeRegionManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vendor/flot/jquery.flot */ "./public/vendor/flot/jquery.flot.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");





var colorModes = {
    gray: {
        themeDependent: true,
        title: 'Gray',
        darkColor: { fill: 'rgba(255, 255, 255, 0.09)', line: 'rgba(255, 255, 255, 0.2)' },
        lightColor: { fill: 'rgba(0, 0, 0, 0.09)', line: 'rgba(0, 0, 0, 0.2)' },
    },
    red: {
        title: 'Red',
        color: { fill: 'rgba(234, 112, 112, 0.12)', line: 'rgba(237, 46, 24, 0.60)' },
    },
    green: {
        title: 'Green',
        color: { fill: 'rgba(11, 237, 50, 0.090)', line: 'rgba(6,163,69, 0.60)' },
    },
    blue: {
        title: 'Blue',
        color: { fill: 'rgba(11, 125, 238, 0.12)', line: 'rgba(11, 125, 238, 0.60)' },
    },
    yellow: {
        title: 'Yellow',
        color: { fill: 'rgba(235, 138, 14, 0.12)', line: 'rgba(247, 149, 32, 0.60)' },
    },
    custom: { title: 'Custom' },
};
function getColorModes() {
    return lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(Object.keys(colorModes), function (key) {
        return {
            key: key,
            value: colorModes[key].title,
        };
    });
}
function getColor(timeRegion, theme) {
    if (Object.keys(colorModes).indexOf(timeRegion.colorMode) === -1) {
        timeRegion.colorMode = 'red';
    }
    if (timeRegion.colorMode === 'custom') {
        return {
            fill: timeRegion.fill && timeRegion.fillColor ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(timeRegion.fillColor, theme) : null,
            line: timeRegion.line && timeRegion.lineColor ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(timeRegion.lineColor, theme) : null,
        };
    }
    var colorMode = colorModes[timeRegion.colorMode];
    if (colorMode.themeDependent === true) {
        return theme === _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["GrafanaThemeType"].Light ? colorMode.lightColor : colorMode.darkColor;
    }
    return {
        fill: timeRegion.fill ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(colorMode.color.fill, theme) : null,
        line: timeRegion.fill ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getColorFromHexRgbOrName"])(colorMode.color.line, theme) : null,
    };
}
var TimeRegionManager = /** @class */ (function () {
    function TimeRegionManager(panelCtrl, theme) {
        if (theme === void 0) { theme = _grafana_ui__WEBPACK_IMPORTED_MODULE_3__["GrafanaThemeType"].Dark; }
        this.panelCtrl = panelCtrl;
        this.theme = theme;
    }
    TimeRegionManager.prototype.draw = function (plot) {
        this.timeRegions = this.panelCtrl.panel.timeRegions;
        this.plot = plot;
    };
    TimeRegionManager.prototype.addFlotOptions = function (options, panel) {
        if (!panel.timeRegions || panel.timeRegions.length === 0) {
            return;
        }
        var tRange = {
            from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(this.panelCtrl.range.from).utc(),
            to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(this.panelCtrl.range.to).utc(),
        };
        var i, hRange, timeRegion, regions, fromStart, fromEnd, timeRegionColor;
        var timeRegionsCopy = panel.timeRegions.map(function (a) { return (tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, a)); });
        for (i = 0; i < timeRegionsCopy.length; i++) {
            timeRegion = timeRegionsCopy[i];
            if (!(timeRegion.fromDayOfWeek || timeRegion.from) && !(timeRegion.toDayOfWeek || timeRegion.to)) {
                continue;
            }
            if (timeRegion.from && !timeRegion.to) {
                timeRegion.to = timeRegion.from;
            }
            if (!timeRegion.from && timeRegion.to) {
                timeRegion.from = timeRegion.to;
            }
            hRange = {
                from: this.parseTimeRange(timeRegion.from),
                to: this.parseTimeRange(timeRegion.to),
            };
            if (!timeRegion.fromDayOfWeek && timeRegion.toDayOfWeek) {
                timeRegion.fromDayOfWeek = timeRegion.toDayOfWeek;
            }
            if (!timeRegion.toDayOfWeek && timeRegion.fromDayOfWeek) {
                timeRegion.toDayOfWeek = timeRegion.fromDayOfWeek;
            }
            if (timeRegion.fromDayOfWeek) {
                hRange.from.dayOfWeek = Number(timeRegion.fromDayOfWeek);
            }
            if (timeRegion.toDayOfWeek) {
                hRange.to.dayOfWeek = Number(timeRegion.toDayOfWeek);
            }
            if (hRange.from.dayOfWeek && hRange.from.h === null && hRange.from.m === null) {
                hRange.from.h = 0;
                hRange.from.m = 0;
                hRange.from.s = 0;
            }
            if (hRange.to.dayOfWeek && hRange.to.h === null && hRange.to.m === null) {
                hRange.to.h = 23;
                hRange.to.m = 59;
                hRange.to.s = 59;
            }
            if (!hRange.from || !hRange.to) {
                continue;
            }
            regions = [];
            fromStart = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(tRange.from);
            fromStart.set('hour', 0);
            fromStart.set('minute', 0);
            fromStart.set('second', 0);
            fromStart.add(hRange.from.h, 'hours');
            fromStart.add(hRange.from.m, 'minutes');
            fromStart.add(hRange.from.s, 'seconds');
            while (fromStart.unix() <= tRange.to.unix()) {
                while (hRange.from.dayOfWeek && hRange.from.dayOfWeek !== fromStart.isoWeekday()) {
                    fromStart.add(24, 'hours');
                }
                if (fromStart.unix() > tRange.to.unix()) {
                    break;
                }
                fromEnd = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_4__["dateTime"])(fromStart);
                if (hRange.from.h <= hRange.to.h) {
                    fromEnd.add(hRange.to.h - hRange.from.h, 'hours');
                }
                else if (hRange.from.h > hRange.to.h) {
                    while (fromEnd.hour() !== hRange.to.h) {
                        fromEnd.add(1, 'hours');
                    }
                }
                else {
                    fromEnd.add(24 - hRange.from.h, 'hours');
                    while (fromEnd.hour() !== hRange.to.h) {
                        fromEnd.add(1, 'hours');
                    }
                }
                fromEnd.set('minute', hRange.to.m);
                fromEnd.set('second', hRange.to.s);
                while (hRange.to.dayOfWeek && hRange.to.dayOfWeek !== fromEnd.isoWeekday()) {
                    fromEnd.add(24, 'hours');
                }
                var outsideRange = (fromStart.unix() < tRange.from.unix() && fromEnd.unix() < tRange.from.unix()) ||
                    (fromStart.unix() > tRange.to.unix() && fromEnd.unix() > tRange.to.unix());
                if (!outsideRange) {
                    regions.push({ from: fromStart.valueOf(), to: fromEnd.valueOf() });
                }
                fromStart.add(24, 'hours');
            }
            timeRegionColor = getColor(timeRegion, this.theme);
            for (var j = 0; j < regions.length; j++) {
                var r = regions[j];
                if (timeRegion.fill) {
                    options.grid.markings.push({
                        xaxis: { from: r.from, to: r.to },
                        color: timeRegionColor.fill,
                    });
                }
                if (timeRegion.line) {
                    options.grid.markings.push({
                        xaxis: { from: r.from, to: r.from },
                        color: timeRegionColor.line,
                    });
                    options.grid.markings.push({
                        xaxis: { from: r.to, to: r.to },
                        color: timeRegionColor.line,
                    });
                }
            }
        }
    };
    TimeRegionManager.prototype.parseTimeRange = function (str) {
        var timeRegex = /^([\d]+):?(\d{2})?/;
        var result = { h: null, m: null };
        var match = timeRegex.exec(str);
        if (!match) {
            return result;
        }
        if (match.length > 1) {
            result.h = Number(match[1]);
            result.m = 0;
            if (match.length > 2 && match[2] !== undefined) {
                result.m = Number(match[2]);
            }
            if (result.h > 23) {
                result.h = 23;
            }
            if (result.m > 59) {
                result.m = 59;
            }
        }
        return result;
    };
    return TimeRegionManager;
}());



/***/ }),

/***/ "./public/app/plugins/panel/graph/time_regions_form.ts":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/graph/time_regions_form.ts ***!
  \*************************************************************/
/*! exports provided: TimeRegionFormCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimeRegionFormCtrl", function() { return TimeRegionFormCtrl; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _time_region_manager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./time_region_manager */ "./public/app/plugins/panel/graph/time_region_manager.ts");


var TimeRegionFormCtrl = /** @class */ (function () {
    /** @ngInject */
    function TimeRegionFormCtrl($scope) {
        var _this = this;
        this.panel = this.panelCtrl.panel;
        var unbindDestroy = $scope.$on('$destroy', function () {
            _this.panelCtrl.editingTimeRegions = false;
            _this.panelCtrl.render();
            unbindDestroy();
        });
        this.colorModes = Object(_time_region_manager__WEBPACK_IMPORTED_MODULE_1__["getColorModes"])();
        this.panelCtrl.editingTimeRegions = true;
    }
    TimeRegionFormCtrl.prototype.render = function () {
        this.panelCtrl.render();
    };
    TimeRegionFormCtrl.prototype.addTimeRegion = function () {
        this.panel.timeRegions.push({
            op: 'time',
            fromDayOfWeek: undefined,
            from: undefined,
            toDayOfWeek: undefined,
            to: undefined,
            colorMode: 'background6',
            fill: true,
            line: false,
            // Default colors for new
            fillColor: 'rgba(234, 112, 112, 0.12)',
            lineColor: 'rgba(237, 46, 24, 0.60)',
        });
        this.panelCtrl.render();
    };
    TimeRegionFormCtrl.prototype.removeTimeRegion = function (index) {
        this.panel.timeRegions.splice(index, 1);
        this.panelCtrl.render();
    };
    TimeRegionFormCtrl.prototype.onFillColorChange = function (index) {
        var _this = this;
        return function (newColor) {
            _this.panel.timeRegions[index].fillColor = newColor;
            _this.render();
        };
    };
    TimeRegionFormCtrl.prototype.onLineColorChange = function (index) {
        var _this = this;
        return function (newColor) {
            _this.panel.timeRegions[index].lineColor = newColor;
            _this.render();
        };
    };
    return TimeRegionFormCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].directive('graphTimeRegionForm', function () {
    return {
        restrict: 'E',
        templateUrl: 'public/app/plugins/panel/graph/time_regions_form.html',
        controller: TimeRegionFormCtrl,
        bindToController: true,
        controllerAs: 'ctrl',
        scope: {
            panelCtrl: '=',
        },
    };
});


/***/ }),

/***/ "./public/app/plugins/panel/graph2/GraphLegendEditor.tsx":
/*!***************************************************************!*\
  !*** ./public/app/plugins/panel/graph2/GraphLegendEditor.tsx ***!
  \***************************************************************/
/*! exports provided: GraphLegendEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphLegendEditor", function() { return GraphLegendEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");



var GraphLegendEditor = function (props) {
    var options = props.options, onChange = props.onChange;
    var onStatsChanged = function (stats) {
        onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { stats: stats }));
    };
    var onOptionToggle = function (option) { return function (event) {
        var newOption = {};
        if (!event) {
            return;
        }
        // TODO: fix the ignores
        // @ts-ignore
        newOption[option] = event.target.checked;
        if (option === 'placement') {
            // @ts-ignore
            newOption[option] = event.target.checked ? 'right' : 'under';
        }
        onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, newOption));
    }; };
    var labelWidth = 8;
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Legend" },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "section gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h4", null, "Options"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Show legend", labelClass: "width-" + labelWidth, checked: options.isVisible, onChange: onOptionToggle('isVisible') }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Display as table", labelClass: "width-" + labelWidth, checked: options.asTable, onChange: onOptionToggle('asTable') }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "To the right", labelClass: "width-" + labelWidth, checked: options.placement === 'right', onChange: onOptionToggle('placement') })),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "section gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h4", null, "Show"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["StatsPicker"], { allowMultiple: true, stats: options.stats ? options.stats : [], onChange: onStatsChanged, placeholder: 'Pick Values' })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-label" }, "Decimals"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Input"], { className: "gf-form-input width-5", type: "number", value: options.decimals, placeholder: "Auto", onChange: function (event) {
                        onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { decimals: parseInt(event.target.value, 10) }));
                    } }))),
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "section gf-form-group" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h4", null, "Hidden series"),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "With only zeros", checked: !!options.hideZero, onChange: onOptionToggle('hideZero') }))));
};


/***/ }),

/***/ "./public/app/plugins/panel/graph2/GraphPanel.tsx":
/*!********************************************************!*\
  !*** ./public/app/plugins/panel/graph2/GraphPanel.tsx ***!
  \********************************************************/
/*! exports provided: GraphPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphPanel", function() { return GraphPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _GraphPanelController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./GraphPanelController */ "./public/app/plugins/panel/graph2/GraphPanelController.tsx");
/* harmony import */ var _grafana_ui_src_components_Legend_Legend__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui/src/components/Legend/Legend */ "./packages/grafana-ui/src/components/Legend/Legend.tsx");





var GraphPanel = function (_a) {
    var data = _a.data, timeRange = _a.timeRange, timeZone = _a.timeZone, width = _a.width, height = _a.height, options = _a.options, onOptionsChange = _a.onOptionsChange, onChangeTimeRange = _a.onChangeTimeRange;
    if (!data) {
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "panel-empty" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("p", null, "No data found in response")));
    }
    var _b = options.graph, showLines = _b.showLines, showBars = _b.showBars, showPoints = _b.showPoints, legendOptions = options.legend;
    var graphProps = {
        showBars: showBars,
        showLines: showLines,
        showPoints: showPoints,
    };
    var asTable = legendOptions.asTable, isVisible = legendOptions.isVisible, legendProps = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](legendOptions, ["asTable", "isVisible"]);
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_GraphPanelController__WEBPACK_IMPORTED_MODULE_3__["GraphPanelController"], { data: data, options: options, onOptionsChange: onOptionsChange, onChangeTimeRange: onChangeTimeRange }, function (_a) {
        var onSeriesToggle = _a.onSeriesToggle, onHorizontalRegionSelected = _a.onHorizontalRegionSelected, controllerApi = tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"](_a, ["onSeriesToggle", "onHorizontalRegionSelected"]);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["GraphWithLegend"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ timeRange: timeRange, timeZone: timeZone, width: width, height: height, displayMode: asTable ? _grafana_ui_src_components_Legend_Legend__WEBPACK_IMPORTED_MODULE_4__["LegendDisplayMode"].Table : _grafana_ui_src_components_Legend_Legend__WEBPACK_IMPORTED_MODULE_4__["LegendDisplayMode"].List, isLegendVisible: isVisible, sortLegendBy: legendOptions.sortBy, sortLegendDesc: legendOptions.sortDesc, onSeriesToggle: onSeriesToggle, onHorizontalRegionSelected: onHorizontalRegionSelected }, graphProps, legendProps, controllerApi)));
    }));
};


/***/ }),

/***/ "./public/app/plugins/panel/graph2/GraphPanelController.tsx":
/*!******************************************************************!*\
  !*** ./public/app/plugins/panel/graph2/GraphPanelController.tsx ***!
  \******************************************************************/
/*! exports provided: GraphPanelController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphPanelController", function() { return GraphPanelController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./getGraphSeriesModel */ "./public/app/plugins/panel/graph2/getGraphSeriesModel.ts");




var GraphPanelController = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GraphPanelController, _super);
    function GraphPanelController(props) {
        var _this = _super.call(this, props) || this;
        _this.onSeriesColorChange = _this.onSeriesColorChange.bind(_this);
        _this.onSeriesAxisToggle = _this.onSeriesAxisToggle.bind(_this);
        _this.onToggleSort = _this.onToggleSort.bind(_this);
        _this.onHorizontalRegionSelected = _this.onHorizontalRegionSelected.bind(_this);
        _this.state = {
            graphSeriesModel: Object(_getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_3__["getGraphSeriesModel"])(props.data.series, props.options.series, props.options.graph, props.options.legend),
        };
        return _this;
    }
    GraphPanelController.getDerivedStateFromProps = function (props, state) {
        return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, state, { graphSeriesModel: Object(_getGraphSeriesModel__WEBPACK_IMPORTED_MODULE_3__["getGraphSeriesModel"])(props.data.series, props.options.series, props.options.graph, props.options.legend) });
    };
    GraphPanelController.prototype.onSeriesOptionsUpdate = function (label, optionsUpdate) {
        var _a = this.props, onOptionsChange = _a.onOptionsChange, options = _a.options;
        var updatedSeriesOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options.series);
        updatedSeriesOptions[label] = optionsUpdate;
        onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { series: updatedSeriesOptions }));
    };
    GraphPanelController.prototype.onSeriesAxisToggle = function (label, yAxis) {
        var series = this.props.options.series;
        var seriesOptionsUpdate = series[label]
            ? tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series[label], { yAxis: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series[label].yAxis, { index: yAxis }) }) : {
            yAxis: {
                index: yAxis,
            },
        };
        this.onSeriesOptionsUpdate(label, seriesOptionsUpdate);
    };
    GraphPanelController.prototype.onSeriesColorChange = function (label, color) {
        var series = this.props.options.series;
        var seriesOptionsUpdate = series[label]
            ? tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, series[label], { color: color }) : {
            color: color,
        };
        this.onSeriesOptionsUpdate(label, seriesOptionsUpdate);
    };
    GraphPanelController.prototype.onToggleSort = function (sortBy) {
        var _a = this.props, onOptionsChange = _a.onOptionsChange, options = _a.options;
        onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { legend: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options.legend, { sortBy: sortBy, sortDesc: sortBy === options.legend.sortBy ? !options.legend.sortDesc : false }) }));
    };
    GraphPanelController.prototype.onHorizontalRegionSelected = function (from, to) {
        var onChangeTimeRange = this.props.onChangeTimeRange;
        onChangeTimeRange({ from: from, to: to });
    };
    GraphPanelController.prototype.render = function () {
        var _this = this;
        var children = this.props.children;
        var graphSeriesModel = this.state.graphSeriesModel;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["GraphSeriesToggler"], { series: graphSeriesModel }, function (_a) {
            var onSeriesToggle = _a.onSeriesToggle, toggledSeries = _a.toggledSeries;
            return children({
                series: toggledSeries,
                onSeriesColorChange: _this.onSeriesColorChange,
                onSeriesAxisToggle: _this.onSeriesAxisToggle,
                onToggleSort: _this.onToggleSort,
                onSeriesToggle: onSeriesToggle,
                onHorizontalRegionSelected: _this.onHorizontalRegionSelected,
            });
        }));
    };
    return GraphPanelController;
}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component));



/***/ }),

/***/ "./public/app/plugins/panel/graph2/GraphPanelEditor.tsx":
/*!**************************************************************!*\
  !*** ./public/app/plugins/panel/graph2/GraphPanelEditor.tsx ***!
  \**************************************************************/
/*! exports provided: GraphPanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GraphPanelEditor", function() { return GraphPanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _GraphLegendEditor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./GraphLegendEditor */ "./public/app/plugins/panel/graph2/GraphLegendEditor.tsx");


// Types


var GraphPanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GraphPanelEditor, _super);
    function GraphPanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onGraphOptionsChange = function (options) {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { graph: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.graph, options) }));
        };
        _this.onLegendOptionsChange = function (options) {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { legend: options }));
        };
        _this.onToggleLines = function () {
            _this.onGraphOptionsChange({ showLines: !_this.props.options.graph.showLines });
        };
        _this.onToggleBars = function () {
            _this.onGraphOptionsChange({ showBars: !_this.props.options.graph.showBars });
        };
        _this.onTogglePoints = function () {
            _this.onGraphOptionsChange({ showPoints: !_this.props.options.graph.showPoints });
        };
        return _this;
    }
    GraphPanelEditor.prototype.render = function () {
        var _a = this.props.options.graph, showBars = _a.showBars, showPoints = _a.showPoints, showLines = _a.showLines;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "section gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", { className: "section-heading" }, "Draw Modes"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Lines", labelClass: "width-5", checked: showLines, onChange: this.onToggleLines }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Bars", labelClass: "width-5", checked: showBars, onChange: this.onToggleBars }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Points", labelClass: "width-5", checked: showPoints, onChange: this.onTogglePoints })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_GraphLegendEditor__WEBPACK_IMPORTED_MODULE_3__["GraphLegendEditor"], { options: this.props.options.legend, onChange: this.onLegendOptionsChange })));
    };
    return GraphPanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/graph2/getGraphSeriesModel.ts":
/*!****************************************************************!*\
  !*** ./public/app/plugins/panel/graph2/getGraphSeriesModel.ts ***!
  \****************************************************************/
/*! exports provided: getGraphSeriesModel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getGraphSeriesModel", function() { return getGraphSeriesModel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");



var getGraphSeriesModel = function (dataFrames, seriesOptions, graphOptions, legendOptions) {
    var e_1, _a, e_2, _b;
    var graphs = [];
    var displayProcessor = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getDisplayProcessor"])({
        config: {
            decimals: legendOptions.decimals,
        },
    });
    try {
        for (var dataFrames_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](dataFrames), dataFrames_1_1 = dataFrames_1.next(); !dataFrames_1_1.done; dataFrames_1_1 = dataFrames_1.next()) {
            var series = dataFrames_1_1.value;
            var timeField = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["getTimeField"])(series).timeField;
            if (!timeField) {
                continue;
            }
            var _loop_1 = function (field) {
                if (field.type !== _grafana_data__WEBPACK_IMPORTED_MODULE_2__["FieldType"].number) {
                    return "continue";
                }
                // Use external calculator just to make sure it works :)
                var points = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getFlotPairs"])({
                    xField: timeField,
                    yField: field,
                    nullValueMode: _grafana_data__WEBPACK_IMPORTED_MODULE_2__["NullValueMode"].Null,
                });
                if (points.length > 0) {
                    var seriesStats_1 = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["reduceField"])({ field: field, reducers: legendOptions.stats });
                    var statsDisplayValues = void 0;
                    if (legendOptions.stats) {
                        statsDisplayValues = legendOptions.stats.map(function (stat) {
                            var statDisplayValue = displayProcessor(seriesStats_1[stat]);
                            return tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, statDisplayValue, { text: statDisplayValue.text, title: stat });
                        });
                    }
                    var seriesColor = seriesOptions[field.name] && seriesOptions[field.name].color
                        ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getColorFromHexRgbOrName"])(seriesOptions[field.name].color)
                        : _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["colors"][graphs.length % _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["colors"].length];
                    graphs.push({
                        label: field.name,
                        data: points,
                        color: seriesColor,
                        info: statsDisplayValues,
                        isVisible: true,
                        yAxis: {
                            index: (seriesOptions[field.name] && seriesOptions[field.name].yAxis) || 1,
                        },
                    });
                }
            };
            try {
                for (var _c = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](series.fields)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var field = _d.value;
                    _loop_1(field);
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (dataFrames_1_1 && !dataFrames_1_1.done && (_a = dataFrames_1.return)) _a.call(dataFrames_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return graphs;
};


/***/ }),

/***/ "./public/app/plugins/panel/graph2/module.tsx":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/graph2/module.tsx ***!
  \****************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _GraphPanelEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./GraphPanelEditor */ "./public/app/plugins/panel/graph2/GraphPanelEditor.tsx");
/* harmony import */ var _GraphPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./GraphPanel */ "./public/app/plugins/panel/graph2/GraphPanel.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/graph2/types.ts");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_GraphPanel__WEBPACK_IMPORTED_MODULE_2__["GraphPanel"]).setDefaults(_types__WEBPACK_IMPORTED_MODULE_3__["defaults"]).setEditor(_GraphPanelEditor__WEBPACK_IMPORTED_MODULE_1__["GraphPanelEditor"]);


/***/ }),

/***/ "./public/app/plugins/panel/graph2/types.ts":
/*!**************************************************!*\
  !*** ./public/app/plugins/panel/graph2/types.ts ***!
  \**************************************************/
/*! exports provided: defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
var defaults = {
    graph: {
        showBars: false,
        showLines: true,
        showPoints: false,
    },
    legend: {
        asTable: false,
        isVisible: true,
        placement: 'under',
    },
    series: {},
};


/***/ }),

/***/ "./public/app/plugins/panel/heatmap/axes_editor.ts":
/*!*********************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/axes_editor.ts ***!
  \*********************************************************/
/*! exports provided: AxesEditorCtrl, axesEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesEditorCtrl", function() { return AxesEditorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "axesEditor", function() { return axesEditor; });
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");

var AxesEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function AxesEditorCtrl($scope, uiSegmentSrv) {
        $scope.editor = this;
        this.panelCtrl = $scope.ctrl;
        this.panel = this.panelCtrl.panel;
        this.unitFormats = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_0__["default"].getUnitFormats();
        this.logScales = {
            linear: 1,
            'log (base 2)': 2,
            'log (base 10)': 10,
            'log (base 32)': 32,
            'log (base 1024)': 1024,
        };
        this.dataFormats = {
            'Time series': 'timeseries',
            'Time series buckets': 'tsbuckets',
        };
        this.yBucketBoundModes = {
            Auto: 'auto',
            Upper: 'upper',
            Lower: 'lower',
            Middle: 'middle',
        };
    }
    AxesEditorCtrl.prototype.setUnitFormat = function (subItem) {
        this.panel.yAxis.format = subItem.value;
        this.panelCtrl.render();
    };
    return AxesEditorCtrl;
}());

/** @ngInject */
function axesEditor() {
    'use strict';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'public/app/plugins/panel/heatmap/partials/axes_editor.html',
        controller: AxesEditorCtrl,
    };
}


/***/ }),

/***/ "./public/app/plugins/panel/heatmap/color_legend.ts":
/*!**********************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/color_legend.ts ***!
  \**********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! d3 */ "./node_modules/d3/index.js");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/ticks */ "./public/app/core/utils/ticks.ts");
/* harmony import */ var _color_scale__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./color_scale */ "./public/app/plugins/panel/heatmap/color_scale.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");








var LEGEND_HEIGHT_PX = 6;
var LEGEND_WIDTH_PX = 100;
var LEGEND_TICK_SIZE = 0;
var LEGEND_VALUE_MARGIN = 0;
var LEGEND_PADDING_LEFT = 10;
var LEGEND_SEGMENT_WIDTH = 10;
/**
 * Color legend for heatmap editor.
 */
app_core_core_module__WEBPACK_IMPORTED_MODULE_6__["default"].directive('colorLegend', function () {
    return {
        restrict: 'E',
        template: '<div class="heatmap-color-legend"><svg width="16.5rem" height="24px"></svg></div>',
        link: function (scope, elem, attrs) {
            var ctrl = scope.ctrl;
            var panel = scope.ctrl.panel;
            render();
            ctrl.events.on('render', function () {
                render();
            });
            function render() {
                var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
                var legendWidth = Math.floor(legendElem.outerWidth());
                if (panel.color.mode === 'spectrum') {
                    var colorScheme = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(ctrl.colorSchemes, {
                        value: panel.color.colorScheme,
                    });
                    var colorScale = Object(_color_scale__WEBPACK_IMPORTED_MODULE_5__["getColorScale"])(colorScheme, app_core_core__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].user.lightTheme, legendWidth);
                    drawSimpleColorLegend(elem, colorScale);
                }
                else if (panel.color.mode === 'opacity') {
                    var colorOptions = panel.color;
                    drawSimpleOpacityLegend(elem, colorOptions);
                }
            }
        },
    };
});
/**
 * Heatmap legend with scale values.
 */
app_core_core_module__WEBPACK_IMPORTED_MODULE_6__["default"].directive('heatmapLegend', function () {
    return {
        restrict: 'E',
        template: "<div class=\"heatmap-color-legend\"><svg width=\"" + LEGEND_WIDTH_PX + "px\" height=\"" + LEGEND_HEIGHT_PX + "px\"></svg></div>",
        link: function (scope, elem, attrs) {
            var ctrl = scope.ctrl;
            var panel = scope.ctrl.panel;
            render();
            ctrl.events.on('render', function () {
                render();
            });
            function render() {
                clearLegend(elem);
                if (!lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isEmpty(ctrl.data) && !lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isEmpty(ctrl.data.cards)) {
                    var cardStats = ctrl.data.cardStats;
                    var rangeFrom = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNil(panel.color.min) ? Math.min(cardStats.min, 0) : panel.color.min;
                    var rangeTo = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNil(panel.color.max) ? cardStats.max : panel.color.max;
                    var maxValue = cardStats.max;
                    var minValue = cardStats.min;
                    if (panel.color.mode === 'spectrum') {
                        var colorScheme = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(ctrl.colorSchemes, {
                            value: panel.color.colorScheme,
                        });
                        drawColorLegend(elem, colorScheme, rangeFrom, rangeTo, maxValue, minValue);
                    }
                    else if (panel.color.mode === 'opacity') {
                        var colorOptions = panel.color;
                        drawOpacityLegend(elem, colorOptions, rangeFrom, rangeTo, maxValue, minValue);
                    }
                }
            }
        },
    };
});
function drawColorLegend(elem, colorScheme, rangeFrom, rangeTo, maxValue, minValue) {
    var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
    var legend = d3__WEBPACK_IMPORTED_MODULE_2__["select"](legendElem.get(0));
    clearLegend(elem);
    var legendWidth = Math.floor(legendElem.outerWidth()) - 30;
    var legendHeight = legendElem.attr('height');
    var rangeStep = ((rangeTo - rangeFrom) / legendWidth) * LEGEND_SEGMENT_WIDTH;
    var widthFactor = legendWidth / (rangeTo - rangeFrom);
    var valuesRange = d3__WEBPACK_IMPORTED_MODULE_2__["range"](rangeFrom, rangeTo, rangeStep);
    var colorScale = Object(_color_scale__WEBPACK_IMPORTED_MODULE_5__["getColorScale"])(colorScheme, app_core_core__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].user.lightTheme, maxValue, minValue);
    legend
        .append('g')
        .attr('class', 'legend-color-bar')
        .attr('transform', 'translate(' + LEGEND_PADDING_LEFT + ',0)')
        .selectAll('.heatmap-color-legend-rect')
        .data(valuesRange)
        .enter()
        .append('rect')
        .attr('x', function (d) { return Math.round((d - rangeFrom) * widthFactor); })
        .attr('y', 0)
        .attr('width', Math.round(rangeStep * widthFactor + 1)) // Overlap rectangles to prevent gaps
        .attr('height', legendHeight)
        .attr('stroke-width', 0)
        .attr('fill', function (d) { return colorScale(d); });
    drawLegendValues(elem, rangeFrom, rangeTo, maxValue, minValue, legendWidth, valuesRange);
}
function drawOpacityLegend(elem, options, rangeFrom, rangeTo, maxValue, minValue) {
    var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
    var legend = d3__WEBPACK_IMPORTED_MODULE_2__["select"](legendElem.get(0));
    clearLegend(elem);
    var legendWidth = Math.floor(legendElem.outerWidth()) - 30;
    var legendHeight = legendElem.attr('height');
    var rangeStep = ((rangeTo - rangeFrom) / legendWidth) * LEGEND_SEGMENT_WIDTH;
    var widthFactor = legendWidth / (rangeTo - rangeFrom);
    var valuesRange = d3__WEBPACK_IMPORTED_MODULE_2__["range"](rangeFrom, rangeTo, rangeStep);
    var opacityScale = Object(_color_scale__WEBPACK_IMPORTED_MODULE_5__["getOpacityScale"])(options, maxValue, minValue);
    legend
        .append('g')
        .attr('class', 'legend-color-bar')
        .attr('transform', 'translate(' + LEGEND_PADDING_LEFT + ',0)')
        .selectAll('.heatmap-opacity-legend-rect')
        .data(valuesRange)
        .enter()
        .append('rect')
        .attr('x', function (d) { return Math.round((d - rangeFrom) * widthFactor); })
        .attr('y', 0)
        .attr('width', Math.round(rangeStep * widthFactor))
        .attr('height', legendHeight)
        .attr('stroke-width', 0)
        .attr('fill', options.cardColor)
        .style('opacity', function (d) { return opacityScale(d); });
    drawLegendValues(elem, rangeFrom, rangeTo, maxValue, minValue, legendWidth, valuesRange);
}
function drawLegendValues(elem, rangeFrom, rangeTo, maxValue, minValue, legendWidth, valuesRange) {
    var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
    var legend = d3__WEBPACK_IMPORTED_MODULE_2__["select"](legendElem.get(0));
    if (legendWidth <= 0 || legendElem.get(0).childNodes.length === 0) {
        return;
    }
    var legendValueScale = d3__WEBPACK_IMPORTED_MODULE_2__["scaleLinear"]()
        .domain([rangeFrom, rangeTo])
        .range([0, legendWidth]);
    var ticks = buildLegendTicks(rangeFrom, rangeTo, maxValue, minValue);
    var xAxis = d3__WEBPACK_IMPORTED_MODULE_2__["axisBottom"](legendValueScale)
        .tickValues(ticks)
        .tickSize(LEGEND_TICK_SIZE);
    var colorRect = legendElem.find(':first-child');
    var posY = getSvgElemHeight(legendElem) + LEGEND_VALUE_MARGIN;
    var posX = getSvgElemX(colorRect) + LEGEND_PADDING_LEFT;
    d3__WEBPACK_IMPORTED_MODULE_2__["select"](legendElem.get(0))
        .append('g')
        .attr('class', 'axis')
        .attr('transform', 'translate(' + posX + ',' + posY + ')')
        .call(xAxis);
    legend
        .select('.axis')
        .select('.domain')
        .remove();
}
function drawSimpleColorLegend(elem, colorScale) {
    var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
    clearLegend(elem);
    var legendWidth = Math.floor(legendElem.outerWidth());
    var legendHeight = legendElem.attr('height');
    if (legendWidth) {
        var valuesNumber = Math.floor(legendWidth / 2);
        var rangeStep = Math.floor(legendWidth / valuesNumber);
        var valuesRange = d3__WEBPACK_IMPORTED_MODULE_2__["range"](0, legendWidth, rangeStep);
        var legend = d3__WEBPACK_IMPORTED_MODULE_2__["select"](legendElem.get(0));
        var legendRects = legend.selectAll('.heatmap-color-legend-rect').data(valuesRange);
        legendRects
            .enter()
            .append('rect')
            .attr('x', function (d) { return d; })
            .attr('y', 0)
            .attr('width', rangeStep + 1) // Overlap rectangles to prevent gaps
            .attr('height', legendHeight)
            .attr('stroke-width', 0)
            .attr('fill', function (d) { return colorScale(d); });
    }
}
function drawSimpleOpacityLegend(elem, options) {
    var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
    clearLegend(elem);
    var legend = d3__WEBPACK_IMPORTED_MODULE_2__["select"](legendElem.get(0));
    var legendWidth = Math.floor(legendElem.outerWidth());
    var legendHeight = legendElem.attr('height');
    if (legendWidth) {
        var legendOpacityScale_1;
        if (options.colorScale === 'linear') {
            legendOpacityScale_1 = d3__WEBPACK_IMPORTED_MODULE_2__["scaleLinear"]()
                .domain([0, legendWidth])
                .range([0, 1]);
        }
        else if (options.colorScale === 'sqrt') {
            legendOpacityScale_1 = d3__WEBPACK_IMPORTED_MODULE_2__["scalePow"]()
                .exponent(options.exponent)
                .domain([0, legendWidth])
                .range([0, 1]);
        }
        var rangeStep = 10;
        var valuesRange = d3__WEBPACK_IMPORTED_MODULE_2__["range"](0, legendWidth, rangeStep);
        var legendRects = legend.selectAll('.heatmap-opacity-legend-rect').data(valuesRange);
        legendRects
            .enter()
            .append('rect')
            .attr('x', function (d) { return d; })
            .attr('y', 0)
            .attr('width', rangeStep)
            .attr('height', legendHeight)
            .attr('stroke-width', 0)
            .attr('fill', Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_7__["getColorFromHexRgbOrName"])(options.cardColor, app_core_core__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].user.lightTheme ? _grafana_ui__WEBPACK_IMPORTED_MODULE_7__["GrafanaThemeType"].Light : _grafana_ui__WEBPACK_IMPORTED_MODULE_7__["GrafanaThemeType"].Dark))
            .style('opacity', function (d) { return legendOpacityScale_1(d); });
    }
}
function clearLegend(elem) {
    var legendElem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(elem).find('svg');
    legendElem.empty();
}
function getSvgElemX(elem) {
    var svgElem = elem.get(0);
    if (svgElem && svgElem.x && svgElem.x.baseVal) {
        return svgElem.x.baseVal.value;
    }
    else {
        return 0;
    }
}
function getSvgElemHeight(elem) {
    var svgElem = elem.get(0);
    if (svgElem && svgElem.height && svgElem.height.baseVal) {
        return svgElem.height.baseVal.value;
    }
    else {
        return 0;
    }
}
function buildLegendTicks(rangeFrom, rangeTo, maxValue, minValue) {
    var range = rangeTo - rangeFrom;
    var tickStepSize = Object(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["tickStep"])(rangeFrom, rangeTo, 3);
    var ticksNum = Math.ceil(range / tickStepSize);
    var firstTick = getFirstCloseTick(rangeFrom, tickStepSize);
    var ticks = [];
    for (var i = 0; i < ticksNum; i++) {
        var current = firstTick + tickStepSize * i;
        // Add user-defined min and max if it had been set
        if (isValueCloseTo(minValue, current, tickStepSize)) {
            ticks.push(minValue);
            continue;
        }
        else if (minValue < current) {
            ticks.push(minValue);
        }
        if (isValueCloseTo(maxValue, current, tickStepSize)) {
            ticks.push(maxValue);
            continue;
        }
        else if (maxValue < current) {
            ticks.push(maxValue);
        }
        ticks.push(current);
    }
    if (!isValueCloseTo(maxValue, rangeTo, tickStepSize)) {
        ticks.push(maxValue);
    }
    ticks.push(rangeTo);
    ticks = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.sortBy(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.uniq(ticks));
    return ticks;
}
function isValueCloseTo(val, valueTo, step) {
    var diff = Math.abs(val - valueTo);
    return diff < step * 0.3;
}
function getFirstCloseTick(minValue, step) {
    if (minValue < 0) {
        return Math.floor(minValue / step) * step;
    }
    return 0;
}


/***/ }),

/***/ "./public/app/plugins/panel/heatmap/color_scale.ts":
/*!*********************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/color_scale.ts ***!
  \*********************************************************/
/*! exports provided: getColorScale, getOpacityScale */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorScale", function() { return getColorScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getOpacityScale", function() { return getOpacityScale; });
/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! d3 */ "./node_modules/d3/index.js");
/* harmony import */ var d3_scale_chromatic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! d3-scale-chromatic */ "./node_modules/d3-scale-chromatic/src/index.js");


function getColorScale(colorScheme, lightTheme, maxValue, minValue) {
    if (minValue === void 0) { minValue = 0; }
    //@ts-ignore
    var colorInterpolator = d3_scale_chromatic__WEBPACK_IMPORTED_MODULE_1__[colorScheme.value];
    var colorScaleInverted = colorScheme.invert === 'always' || colorScheme.invert === (lightTheme ? 'light' : 'dark');
    var start = colorScaleInverted ? maxValue : minValue;
    var end = colorScaleInverted ? minValue : maxValue;
    return d3__WEBPACK_IMPORTED_MODULE_0__["scaleSequential"](colorInterpolator).domain([start, end]);
}
function getOpacityScale(options, maxValue, minValue) {
    if (minValue === void 0) { minValue = 0; }
    var legendOpacityScale;
    if (options.colorScale === 'linear') {
        legendOpacityScale = d3__WEBPACK_IMPORTED_MODULE_0__["scaleLinear"]()
            .domain([minValue, maxValue])
            .range([0, 1]);
    }
    else if (options.colorScale === 'sqrt') {
        legendOpacityScale = d3__WEBPACK_IMPORTED_MODULE_0__["scalePow"]()
            .exponent(options.exponent)
            .domain([minValue, maxValue])
            .range([0, 1]);
    }
    return legendOpacityScale;
}


/***/ }),

/***/ "./public/app/plugins/panel/heatmap/display_editor.ts":
/*!************************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/display_editor.ts ***!
  \************************************************************/
/*! exports provided: HeatmapDisplayEditorCtrl, heatmapDisplayEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HeatmapDisplayEditorCtrl", function() { return HeatmapDisplayEditorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "heatmapDisplayEditor", function() { return heatmapDisplayEditor; });
var HeatmapDisplayEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function HeatmapDisplayEditorCtrl($scope) {
        $scope.editor = this;
        this.panelCtrl = $scope.ctrl;
        this.panel = this.panelCtrl.panel;
        this.panelCtrl.render();
    }
    return HeatmapDisplayEditorCtrl;
}());

/** @ngInject */
function heatmapDisplayEditor() {
    'use strict';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'public/app/plugins/panel/heatmap/partials/display_editor.html',
        controller: HeatmapDisplayEditorCtrl,
    };
}


/***/ }),

/***/ "./public/app/plugins/panel/heatmap/heatmap_ctrl.ts":
/*!**********************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/heatmap_ctrl.ts ***!
  \**********************************************************/
/*! exports provided: HeatmapCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HeatmapCtrl", function() { return HeatmapCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var _axes_editor__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./axes_editor */ "./public/app/plugins/panel/heatmap/axes_editor.ts");
/* harmony import */ var _display_editor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./display_editor */ "./public/app/plugins/panel/heatmap/display_editor.ts");
/* harmony import */ var _rendering__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./rendering */ "./public/app/plugins/panel/heatmap/rendering.ts");
/* harmony import */ var _heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./heatmap_data_converter */ "./public/app/plugins/panel/heatmap/heatmap_data_converter.ts");
/* harmony import */ var app_features_dashboard_state_runRequest__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/features/dashboard/state/runRequest */ "./public/app/features/dashboard/state/runRequest.ts");
/* harmony import */ var _graph_data_processor__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../graph/data_processor */ "./public/app/plugins/panel/graph/data_processor.ts");










var X_BUCKET_NUMBER_DEFAULT = 30;
var Y_BUCKET_NUMBER_DEFAULT = 10;
var panelDefaults = {
    heatmap: {},
    cards: {
        cardPadding: null,
        cardRound: null,
    },
    color: {
        mode: 'spectrum',
        cardColor: '#b4ff00',
        colorScale: 'sqrt',
        exponent: 0.5,
        colorScheme: 'interpolateOranges',
    },
    legend: {
        show: false,
    },
    dataFormat: 'timeseries',
    yBucketBound: 'auto',
    reverseYBuckets: false,
    xAxis: {
        show: true,
    },
    yAxis: {
        show: true,
        format: 'short',
        decimals: null,
        logBase: 1,
        splitFactor: null,
        min: null,
        max: null,
    },
    xBucketSize: null,
    xBucketNumber: null,
    yBucketSize: null,
    yBucketNumber: null,
    tooltip: {
        show: true,
        showHistogram: false,
    },
    highlightCards: true,
    hideZeroBuckets: false,
};
var colorModes = ['opacity', 'spectrum'];
var opacityScales = ['linear', 'sqrt'];
// Schemes from d3-scale-chromatic
// https://github.com/d3/d3-scale-chromatic
var colorSchemes = [
    // Diverging
    { name: 'Spectral', value: 'interpolateSpectral', invert: 'always' },
    { name: 'RdYlGn', value: 'interpolateRdYlGn', invert: 'always' },
    // Sequential (Single Hue)
    { name: 'Blues', value: 'interpolateBlues', invert: 'dark' },
    { name: 'Greens', value: 'interpolateGreens', invert: 'dark' },
    { name: 'Greys', value: 'interpolateGreys', invert: 'dark' },
    { name: 'Oranges', value: 'interpolateOranges', invert: 'dark' },
    { name: 'Purples', value: 'interpolatePurples', invert: 'dark' },
    { name: 'Reds', value: 'interpolateReds', invert: 'dark' },
    // Sequential (Multi-Hue)
    { name: 'Turbo', value: 'interpolateTurbo', invert: 'light' },
    { name: 'Cividis', value: 'interpolateCividis', invert: 'light' },
    { name: 'Viridis', value: 'interpolateViridis', invert: 'light' },
    { name: 'Magma', value: 'interpolateMagma', invert: 'light' },
    { name: 'Inferno', value: 'interpolateInferno', invert: 'light' },
    { name: 'Plasma', value: 'interpolatePlasma', invert: 'light' },
    { name: 'Warm', value: 'interpolateWarm', invert: 'light' },
    { name: 'Cool', value: 'interpolateCool', invert: 'light' },
    { name: 'Cubehelix', value: 'interpolateCubehelixDefault', invert: 'light' },
    { name: 'BuGn', value: 'interpolateBuGn', invert: 'dark' },
    { name: 'BuPu', value: 'interpolateBuPu', invert: 'dark' },
    { name: 'GnBu', value: 'interpolateGnBu', invert: 'dark' },
    { name: 'OrRd', value: 'interpolateOrRd', invert: 'dark' },
    { name: 'PuBuGn', value: 'interpolatePuBuGn', invert: 'dark' },
    { name: 'PuBu', value: 'interpolatePuBu', invert: 'dark' },
    { name: 'PuRd', value: 'interpolatePuRd', invert: 'dark' },
    { name: 'RdPu', value: 'interpolateRdPu', invert: 'dark' },
    { name: 'YlGnBu', value: 'interpolateYlGnBu', invert: 'dark' },
    { name: 'YlGn', value: 'interpolateYlGn', invert: 'dark' },
    { name: 'YlOrBr', value: 'interpolateYlOrBr', invert: 'dark' },
    { name: 'YlOrRd', value: 'interpolateYlOrRd', invert: 'dark' },
];
var dsSupportHistogramSort = ['elasticsearch'];
var HeatmapCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HeatmapCtrl, _super);
    /** @ngInject */
    function HeatmapCtrl($scope, $injector) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.opacityScales = [];
        _this.colorModes = [];
        _this.colorSchemes = [];
        _this.selectionActivated = false;
        lodash__WEBPACK_IMPORTED_MODULE_2___default.a.defaultsDeep(_this.panel, panelDefaults);
        _this.opacityScales = opacityScales;
        _this.colorModes = colorModes;
        _this.colorSchemes = colorSchemes;
        // Use DataFrames
        _this.useDataFrames = true;
        _this.processor = new _graph_data_processor__WEBPACK_IMPORTED_MODULE_9__["DataProcessor"]({
            xaxis: { mode: 'custom' },
            aliasColors: {},
        });
        // Bind grafana panel events
        _this.events.on('render', _this.onRender.bind(_this));
        _this.events.on('data-frames-received', _this.onDataFramesReceived.bind(_this));
        _this.events.on('data-error', _this.onDataError.bind(_this));
        _this.events.on('data-snapshot-load', _this.onSnapshotLoad.bind(_this));
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.onCardColorChange = _this.onCardColorChange.bind(_this);
        return _this;
    }
    HeatmapCtrl.prototype.onInitEditMode = function () {
        this.addEditorTab('Axes', _axes_editor__WEBPACK_IMPORTED_MODULE_4__["axesEditor"], 2);
        this.addEditorTab('Display', _display_editor__WEBPACK_IMPORTED_MODULE_5__["heatmapDisplayEditor"], 3);
        this.unitFormats = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__["default"].getUnitFormats();
    };
    HeatmapCtrl.prototype.zoomOut = function (evt) {
        this.publishAppEvent('zoom-out', 2);
    };
    HeatmapCtrl.prototype.onRender = function () {
        if (!this.range || !this.series) {
            return;
        }
        if (this.panel.dataFormat === 'tsbuckets') {
            this.convertHistogramToHeatmapData();
        }
        else {
            this.convertTimeSeriesToHeatmapData();
        }
    };
    HeatmapCtrl.prototype.convertTimeSeriesToHeatmapData = function () {
        var xBucketSize, yBucketSize, bucketsData, heatmapStats;
        var logBase = this.panel.yAxis.logBase;
        var xBucketNumber = this.panel.xBucketNumber || X_BUCKET_NUMBER_DEFAULT;
        var xBucketSizeByNumber = Math.floor((this.range.to.valueOf() - this.range.from.valueOf()) / xBucketNumber);
        // Parse X bucket size (number or interval)
        var isIntervalString = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__["default"].interval_regex.test(this.panel.xBucketSize);
        if (isIntervalString) {
            xBucketSize = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_3__["default"].interval_to_ms(this.panel.xBucketSize);
        }
        else if (isNaN(Number(this.panel.xBucketSize)) ||
            this.panel.xBucketSize === '' ||
            this.panel.xBucketSize === null) {
            xBucketSize = xBucketSizeByNumber;
        }
        else {
            xBucketSize = Number(this.panel.xBucketSize);
        }
        // Calculate Y bucket size
        heatmapStats = this.parseSeries(this.series);
        var yBucketNumber = this.panel.yBucketNumber || Y_BUCKET_NUMBER_DEFAULT;
        if (logBase !== 1) {
            yBucketSize = this.panel.yAxis.splitFactor;
        }
        else {
            if (heatmapStats.max === heatmapStats.min) {
                if (heatmapStats.max) {
                    yBucketSize = heatmapStats.max / Y_BUCKET_NUMBER_DEFAULT;
                }
                else {
                    yBucketSize = 1;
                }
            }
            else {
                yBucketSize = (heatmapStats.max - heatmapStats.min) / yBucketNumber;
            }
            yBucketSize = this.panel.yBucketSize || yBucketSize;
        }
        bucketsData = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__["convertToHeatMap"])(this.series, yBucketSize, xBucketSize, logBase);
        // Set default Y range if no data
        if (!heatmapStats.min && !heatmapStats.max) {
            heatmapStats = { min: -1, max: 1, minLog: 1 };
            yBucketSize = 1;
        }
        var _a = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__["convertToCards"])(bucketsData, this.panel.hideZeroBuckets), cards = _a.cards, cardStats = _a.cardStats;
        this.data = {
            buckets: bucketsData,
            heatmapStats: heatmapStats,
            xBucketSize: xBucketSize,
            yBucketSize: yBucketSize,
            cards: cards,
            cardStats: cardStats,
        };
    };
    HeatmapCtrl.prototype.convertHistogramToHeatmapData = function () {
        var panelDatasource = this.getPanelDataSourceType();
        var xBucketSize, yBucketSize, bucketsData, tsBuckets;
        // Try to sort series by bucket bound, if datasource doesn't do it.
        if (!lodash__WEBPACK_IMPORTED_MODULE_2___default.a.includes(dsSupportHistogramSort, panelDatasource)) {
            this.series.sort(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__["sortSeriesByLabel"]);
        }
        if (this.panel.reverseYBuckets) {
            this.series.reverse();
        }
        // Convert histogram to heatmap. Each histogram bucket represented by the series which name is
        // a top (or bottom, depends of datasource) bucket bound. Further, these values will be used as Y axis labels.
        bucketsData = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__["histogramToHeatmap"])(this.series);
        tsBuckets = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(this.series, 'label');
        var yBucketBound = this.panel.yBucketBound;
        if ((panelDatasource === 'prometheus' && yBucketBound !== 'lower' && yBucketBound !== 'middle') ||
            yBucketBound === 'upper') {
            // Prometheus labels are upper inclusive bounds, so add empty bottom bucket label.
            tsBuckets = [''].concat(tsBuckets);
        }
        else {
            // Elasticsearch uses labels as lower bucket bounds, so add empty top bucket label.
            // Use this as a default mode as well.
            tsBuckets.push('');
        }
        // Calculate bucket size based on heatmap data
        var xBucketBoundSet = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(lodash__WEBPACK_IMPORTED_MODULE_2___default.a.keys(bucketsData), function (key) { return Number(key); });
        xBucketSize = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__["calculateBucketSize"])(xBucketBoundSet);
        // Always let yBucketSize=1 in 'tsbuckets' mode
        yBucketSize = 1;
        var _a = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_7__["convertToCards"])(bucketsData, this.panel.hideZeroBuckets), cards = _a.cards, cardStats = _a.cardStats;
        this.data = {
            buckets: bucketsData,
            xBucketSize: xBucketSize,
            yBucketSize: yBucketSize,
            tsBuckets: tsBuckets,
            cards: cards,
            cardStats: cardStats,
        };
    };
    HeatmapCtrl.prototype.getPanelDataSourceType = function () {
        if (this.datasource && this.datasource.meta && this.datasource.meta.id) {
            return this.datasource.meta.id;
        }
        else {
            return 'unknown';
        }
    };
    // This should only be called from the snapshot callback
    HeatmapCtrl.prototype.onSnapshotLoad = function (dataList) {
        this.onDataFramesReceived(Object(app_features_dashboard_state_runRequest__WEBPACK_IMPORTED_MODULE_8__["getProcessedDataFrames"])(dataList));
    };
    // Directly support DataFrame
    HeatmapCtrl.prototype.onDataFramesReceived = function (data) {
        var e_1, _a;
        var _this = this;
        this.series = this.processor.getSeriesList({ dataList: data, range: this.range }).map(function (ts) {
            ts.color = null; // remove whatever the processor set
            ts.flotpairs = ts.getFlotPairs(_this.panel.nullPointMode);
            return ts;
        });
        this.dataWarning = null;
        var datapointsCount = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.reduce(this.series, function (sum, series) {
            return sum + series.datapoints.length;
        }, 0);
        if (datapointsCount === 0) {
            this.dataWarning = {
                title: 'No data points',
                tip: 'No datapoints returned from data query',
            };
        }
        else {
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](this.series), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var series = _c.value;
                    if (series.isOutsideRange) {
                        this.dataWarning = {
                            title: 'Data points outside time range',
                            tip: 'Can be caused by timezone mismatch or missing time filter in query',
                        };
                        break;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }
        this.render();
    };
    HeatmapCtrl.prototype.onDataError = function () {
        this.series = [];
        this.render();
    };
    HeatmapCtrl.prototype.onCardColorChange = function (newColor) {
        this.panel.color.cardColor = newColor;
        this.render();
    };
    HeatmapCtrl.prototype.parseSeries = function (series) {
        var min = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.min(lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(series, function (s) { return s.stats.min; }));
        var minLog = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.min(lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(series, function (s) { return s.stats.logmin; }));
        var max = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.max(lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(series, function (s) { return s.stats.max; }));
        return {
            max: max,
            min: min,
            minLog: minLog,
        };
    };
    HeatmapCtrl.prototype.parseHistogramSeries = function (series) {
        var bounds = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(series, function (s) { return Number(s.alias); });
        var min = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.min(bounds);
        var minLog = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.min(bounds);
        var max = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.max(bounds);
        return {
            max: max,
            min: min,
            minLog: minLog,
        };
    };
    HeatmapCtrl.prototype.link = function (scope, elem, attrs, ctrl) {
        Object(_rendering__WEBPACK_IMPORTED_MODULE_6__["default"])(scope, elem, attrs, ctrl);
    };
    HeatmapCtrl.templateUrl = 'module.html';
    return HeatmapCtrl;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_1__["MetricsPanelCtrl"]));



/***/ }),

/***/ "./public/app/plugins/panel/heatmap/heatmap_data_converter.ts":
/*!********************************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/heatmap_data_converter.ts ***!
  \********************************************************************/
/*! exports provided: convertToHeatMap, histogramToHeatmap, convertToCards, mergeZeroBuckets, getValueBucketBound, isHeatmapDataEqual, calculateBucketSize, sortSeriesByLabel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToHeatMap", function() { return convertToHeatMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "histogramToHeatmap", function() { return histogramToHeatmap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertToCards", function() { return convertToCards; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeZeroBuckets", function() { return mergeZeroBuckets; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValueBucketBound", function() { return getValueBucketBound; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeatmapDataEqual", function() { return isHeatmapDataEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateBucketSize", function() { return calculateBucketSize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortSeriesByLabel", function() { return sortSeriesByLabel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


var VALUE_INDEX = 0;
var TIME_INDEX = 1;
/**
 * Convert histogram represented by the list of series to heatmap object.
 * @param seriesList List of time series
 */
function histogramToHeatmap(seriesList) {
    var e_1, _a;
    var heatmap = {};
    for (var i = 0; i < seriesList.length; i++) {
        var series = seriesList[i];
        var bound = i;
        if (isNaN(bound)) {
            return heatmap;
        }
        try {
            for (var _b = (e_1 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](series.datapoints)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var point = _c.value;
                var count = point[VALUE_INDEX];
                var time = point[TIME_INDEX];
                if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isNumber(count)) {
                    continue;
                }
                var bucket = heatmap[time];
                if (!bucket) {
                    bucket = heatmap[time] = { x: time, buckets: {} };
                }
                bucket.buckets[bound] = {
                    y: bound,
                    count: count,
                    bounds: {
                        top: null,
                        bottom: bound,
                    },
                    values: [],
                    points: [],
                };
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    return heatmap;
}
/**
 * Sort series representing histogram by label value.
 */
function sortSeriesByLabel(s1, s2) {
    var label1, label2;
    try {
        // fail if not integer. might happen with bad queries
        label1 = parseHistogramLabel(s1.label);
        label2 = parseHistogramLabel(s2.label);
    }
    catch (err) {
        console.log(err.message || err);
        return 0;
    }
    if (label1 > label2) {
        return 1;
    }
    if (label1 < label2) {
        return -1;
    }
    return 0;
}
function parseHistogramLabel(label) {
    if (label === '+Inf' || label === 'inf') {
        return +Infinity;
    }
    var value = Number(label);
    if (isNaN(value)) {
        throw new Error("Error parsing histogram label: " + label + " is not a number");
    }
    return value;
}
/**
 * Convert buckets into linear array of "cards" - objects, represented heatmap elements.
 * @param  {Object} buckets
 * @return {Object}          Array of "card" objects and stats
 */
function convertToCards(buckets, hideZero) {
    if (hideZero === void 0) { hideZero = false; }
    var min = 0, max = 0;
    var cards = [];
    lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(buckets, function (xBucket) {
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(xBucket.buckets, function (yBucket) {
            var card = {
                x: xBucket.x,
                y: yBucket.y,
                yBounds: yBucket.bounds,
                values: yBucket.values,
                count: yBucket.count,
            };
            if (!hideZero || card.count !== 0) {
                cards.push(card);
            }
            if (cards.length === 1) {
                min = yBucket.count;
                max = yBucket.count;
            }
            min = yBucket.count < min ? yBucket.count : min;
            max = yBucket.count > max ? yBucket.count : max;
        });
    });
    var cardStats = { min: min, max: max };
    return { cards: cards, cardStats: cardStats };
}
/**
 * Special method for log scales. When series converted into buckets with log scale,
 * for simplification, 0 values are converted into 0, not into -Infinity. On the other hand, we mean
 * that all values less than series minimum, is 0 values, and we create special "minimum" bucket for
 * that values (actually, there're no values less than minimum, so this bucket is empty).
 *  8-16|    | ** |    |  * |  **|
 *   4-8|  * |*  *|*   |** *| *  |
 *   2-4| * *|    | ***|    |*   |
 *   1-2|*   |    |    |    |    | This bucket contains minimum series value
 * 0.5-1|____|____|____|____|____| This bucket should be displayed as 0 on graph
 *     0|____|____|____|____|____| This bucket is for 0 values (should actually be -Infinity)
 * So we should merge two bottom buckets into one (0-value bucket).
 *
 * @param  {Object} buckets  Heatmap buckets
 * @param  {Number} minValue Minimum series value
 * @return {Object}          Transformed buckets
 */
function mergeZeroBuckets(buckets, minValue) {
    lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(buckets, function (xBucket) {
        var yBuckets = xBucket.buckets;
        var emptyBucket = {
            bounds: { bottom: 0, top: 0 },
            values: [],
            points: [],
            count: 0,
        };
        var nullBucket = yBuckets[0] || emptyBucket;
        var minBucket = yBuckets[minValue] || emptyBucket;
        var newBucket = {
            y: 0,
            bounds: { bottom: minValue, top: minBucket.bounds.top || minValue },
            values: [],
            points: [],
            count: 0,
        };
        newBucket.points = nullBucket.points.concat(minBucket.points);
        newBucket.values = nullBucket.values.concat(minBucket.values);
        newBucket.count = newBucket.values.length;
        if (newBucket.count === 0) {
            return;
        }
        delete yBuckets[minValue];
        yBuckets[0] = newBucket;
    });
    return buckets;
}
/**
 * Convert set of time series into heatmap buckets
 * @return {Object}    Heatmap object:
 * {
 *   xBucketBound_1: {
 *     x: xBucketBound_1,
 *     buckets: {
 *       yBucketBound_1: {
 *         y: yBucketBound_1,
 *         bounds: {bottom, top}
 *         values: [val_1, val_2, ..., val_K],
 *         points: [[val_Y, val_X, series_name], ..., [...]],
 *         seriesStat: {seriesName_1: val_1, seriesName_2: val_2}
 *       },
 *       ...
 *       yBucketBound_M: {}
 *     },
 *     values: [val_1, val_2, ..., val_K],
 *     points: [
 *       [val_Y, val_X, series_name], (point_1)
 *       ...
 *       [...] (point_K)
 *     ]
 *   },
 *   xBucketBound_2: {},
 *   ...
 *   xBucketBound_N: {}
 * }
 */
function convertToHeatMap(seriesList, yBucketSize, xBucketSize, logBase) {
    var e_2, _a;
    if (logBase === void 0) { logBase = 1; }
    var heatmap = {};
    var _loop_1 = function (series) {
        var datapoints = series.datapoints;
        var seriesName = series.label;
        // Slice series into X axis buckets
        // |    | ** |    |  * |  **|
        // |  * |*  *|*   |** *| *  |
        // |** *|    | ***|    |*   |
        // |____|____|____|____|____|_
        //
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(datapoints, function (point) {
            var bucketBound = getBucketBound(point[TIME_INDEX], xBucketSize);
            pushToXBuckets(heatmap, point, bucketBound, seriesName);
        });
    };
    try {
        for (var seriesList_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](seriesList), seriesList_1_1 = seriesList_1.next(); !seriesList_1_1.done; seriesList_1_1 = seriesList_1.next()) {
            var series = seriesList_1_1.value;
            _loop_1(series);
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (seriesList_1_1 && !seriesList_1_1.done && (_a = seriesList_1.return)) _a.call(seriesList_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    // Slice X axis buckets into Y (value) buckets
    // |  **|     |2|,
    // | *  | --\ |1|,
    // |*   | --/ |1|,
    // |____|     |0|
    //
    lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(heatmap, function (xBucket) {
        if (logBase !== 1) {
            xBucket.buckets = convertToLogScaleValueBuckets(xBucket, yBucketSize, logBase);
        }
        else {
            xBucket.buckets = convertToValueBuckets(xBucket, yBucketSize);
        }
    });
    return heatmap;
}
function pushToXBuckets(buckets, point, bucketNum, seriesName) {
    var value = point[VALUE_INDEX];
    if (value === null || value === undefined || isNaN(value)) {
        return;
    }
    // Add series name to point for future identification
    var pointExt = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.concat(point, seriesName);
    if (buckets[bucketNum] && buckets[bucketNum].values) {
        buckets[bucketNum].values.push(value);
        buckets[bucketNum].points.push(pointExt);
    }
    else {
        buckets[bucketNum] = {
            x: bucketNum,
            values: [value],
            points: [pointExt],
        };
    }
}
function pushToYBuckets(buckets, bucketNum, value, point, bounds) {
    var count = 1;
    // Use the 3rd argument as scale/count
    if (point.length > 3) {
        count = parseInt(point[2], 10);
    }
    if (buckets[bucketNum]) {
        buckets[bucketNum].values.push(value);
        buckets[bucketNum].points.push(point);
        buckets[bucketNum].count += count;
    }
    else {
        buckets[bucketNum] = {
            y: bucketNum,
            bounds: bounds,
            values: [value],
            points: [point],
            count: count,
        };
    }
}
function getValueBucketBound(value, yBucketSize, logBase) {
    if (logBase === 1) {
        return getBucketBound(value, yBucketSize);
    }
    else {
        return getLogScaleBucketBound(value, yBucketSize, logBase);
    }
}
/**
 * Find bucket for given value (for linear scale)
 */
function getBucketBounds(value, bucketSize) {
    var bottom, top;
    bottom = Math.floor(value / bucketSize) * bucketSize;
    top = (Math.floor(value / bucketSize) + 1) * bucketSize;
    return { bottom: bottom, top: top };
}
function getBucketBound(value, bucketSize) {
    var bounds = getBucketBounds(value, bucketSize);
    return bounds.bottom;
}
function convertToValueBuckets(xBucket, bucketSize) {
    var values = xBucket.values;
    var points = xBucket.points;
    var buckets = {};
    lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(values, function (val, index) {
        var bounds = getBucketBounds(val, bucketSize);
        var bucketNum = bounds.bottom;
        pushToYBuckets(buckets, bucketNum, val, points[index], bounds);
    });
    return buckets;
}
/**
 * Find bucket for given value (for log scales)
 */
function getLogScaleBucketBounds(value, yBucketSplitFactor, logBase) {
    var top, bottom;
    if (value === 0) {
        return { bottom: 0, top: 0 };
    }
    var valueLog = logp(value, logBase);
    var pow, powTop;
    if (yBucketSplitFactor === 1 || !yBucketSplitFactor) {
        pow = Math.floor(valueLog);
        powTop = pow + 1;
    }
    else {
        var additionalBucketSize = 1 / yBucketSplitFactor;
        var additionalLog = valueLog - Math.floor(valueLog);
        additionalLog = Math.floor(additionalLog / additionalBucketSize) * additionalBucketSize;
        pow = Math.floor(valueLog) + additionalLog;
        powTop = pow + additionalBucketSize;
    }
    bottom = Math.pow(logBase, pow);
    top = Math.pow(logBase, powTop);
    return { bottom: bottom, top: top };
}
function getLogScaleBucketBound(value, yBucketSplitFactor, logBase) {
    var bounds = getLogScaleBucketBounds(value, yBucketSplitFactor, logBase);
    return bounds.bottom;
}
function convertToLogScaleValueBuckets(xBucket, yBucketSplitFactor, logBase) {
    var values = xBucket.values;
    var points = xBucket.points;
    var buckets = {};
    lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(values, function (val, index) {
        var bounds = getLogScaleBucketBounds(val, yBucketSplitFactor, logBase);
        var bucketNum = bounds.bottom;
        pushToYBuckets(buckets, bucketNum, val, points[index], bounds);
    });
    return buckets;
}
/**
 * Logarithm for custom base
 * @param value
 * @param base logarithm base
 */
function logp(value, base) {
    return Math.log(value) / Math.log(base);
}
/**
 * Calculate size of Y bucket from given buckets bounds.
 * @param bounds Array of Y buckets bounds
 * @param logBase Logarithm base
 */
function calculateBucketSize(bounds, logBase) {
    if (logBase === void 0) { logBase = 1; }
    var bucketSize = Infinity;
    if (bounds.length === 0) {
        return 0;
    }
    else if (bounds.length === 1) {
        return bounds[0];
    }
    else {
        bounds = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(bounds);
        for (var i = 1; i < bounds.length; i++) {
            var distance = getDistance(bounds[i], bounds[i - 1], logBase);
            bucketSize = distance < bucketSize ? distance : bucketSize;
        }
    }
    return bucketSize;
}
/**
 * Calculate distance between two numbers in given scale (linear or logarithmic).
 * @param a
 * @param b
 * @param logBase
 */
function getDistance(a, b, logBase) {
    if (logBase === void 0) { logBase = 1; }
    if (logBase === 1) {
        // Linear distance
        return Math.abs(b - a);
    }
    else {
        // logarithmic distance
        var ratio = Math.max(a, b) / Math.min(a, b);
        return logp(ratio, logBase);
    }
}
/**
 * Compare two heatmap data objects
 * @param objA
 * @param objB
 */
function isHeatmapDataEqual(objA, objB) {
    var isEql = !emptyXOR(objA, objB);
    lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(objA, function (xBucket, x) {
        if (objB[x]) {
            if (emptyXOR(xBucket.buckets, objB[x].buckets)) {
                isEql = false;
                return false;
            }
            lodash__WEBPACK_IMPORTED_MODULE_1___default.a.forEach(xBucket.buckets, function (yBucket, y) {
                if (objB[x].buckets && objB[x].buckets[y]) {
                    if (objB[x].buckets[y].values) {
                        isEql = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEqual(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(yBucket.values), lodash__WEBPACK_IMPORTED_MODULE_1___default.a.sortBy(objB[x].buckets[y].values));
                        if (!isEql) {
                            return false;
                        }
                        else {
                            return true;
                        }
                    }
                    else {
                        isEql = false;
                        return false;
                    }
                }
                else {
                    isEql = false;
                    return false;
                }
            });
            if (!isEql) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            isEql = false;
            return false;
        }
    });
    return isEql;
}
function emptyXOR(foo, bar) {
    return (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEmpty(foo) || lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEmpty(bar)) && !(lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEmpty(foo) && lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isEmpty(bar));
}



/***/ }),

/***/ "./public/app/plugins/panel/heatmap/heatmap_tooltip.ts":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/heatmap_tooltip.ts ***!
  \*************************************************************/
/*! exports provided: HeatmapTooltip */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HeatmapTooltip", function() { return HeatmapTooltip; });
/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! d3 */ "./node_modules/d3/index.js");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _heatmap_data_converter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./heatmap_data_converter */ "./public/app/plugins/panel/heatmap/heatmap_data_converter.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");





var TOOLTIP_PADDING_X = 30;
var TOOLTIP_PADDING_Y = 5;
var HISTOGRAM_WIDTH = 160;
var HISTOGRAM_HEIGHT = 40;
var HeatmapTooltip = /** @class */ (function () {
    function HeatmapTooltip(elem, scope) {
        this.scope = scope;
        this.dashboard = scope.ctrl.dashboard;
        this.panelCtrl = scope.ctrl;
        this.panel = scope.ctrl.panel;
        this.heatmapPanel = elem;
        this.mouseOverBucket = false;
        this.originalFillColor = null;
        elem.on('mouseleave', this.onMouseLeave.bind(this));
    }
    HeatmapTooltip.prototype.onMouseLeave = function () {
        this.destroy();
    };
    HeatmapTooltip.prototype.onMouseMove = function (e) {
        if (!this.panel.tooltip.show) {
            return;
        }
        this.move(e);
    };
    HeatmapTooltip.prototype.add = function () {
        this.tooltip = d3__WEBPACK_IMPORTED_MODULE_0__["select"]('body')
            .append('div')
            .attr('class', 'heatmap-tooltip graph-tooltip grafana-tooltip');
    };
    HeatmapTooltip.prototype.destroy = function () {
        if (this.tooltip) {
            this.tooltip.remove();
        }
        this.tooltip = null;
    };
    HeatmapTooltip.prototype.show = function (pos, data) {
        if (!this.panel.tooltip.show || !data) {
            return;
        }
        // shared tooltip mode
        if (pos.panelRelY) {
            return;
        }
        var _a = this.getBucketIndexes(pos, data), xBucketIndex = _a.xBucketIndex, yBucketIndex = _a.yBucketIndex;
        if (!data.buckets[xBucketIndex]) {
            this.destroy();
            return;
        }
        if (!this.tooltip) {
            this.add();
        }
        var boundBottom, boundTop, valuesNumber;
        var xData = data.buckets[xBucketIndex];
        // Search in special 'zero' bucket also
        var yData = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(xData.buckets, function (bucket, bucketIndex) {
            return bucket.bounds.bottom === yBucketIndex || bucketIndex === yBucketIndex.toString();
        });
        var tooltipTimeFormat = 'YYYY-MM-DD HH:mm:ss';
        var time = this.dashboard.formatDate(xData.x, tooltipTimeFormat);
        // Decimals override. Code from panel/graph/graph.ts
        var countValueFormatter, bucketBoundFormatter;
        if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isNumber(this.panel.tooltipDecimals)) {
            countValueFormatter = this.countValueFormatter(this.panel.tooltipDecimals, null);
            bucketBoundFormatter = this.panelCtrl.tickValueFormatter(this.panelCtrl.decimals, null);
        }
        else {
            // auto decimals
            // legend and tooltip gets one more decimal precision
            // than graph legend ticks
            var decimals = (this.panelCtrl.decimals || -1) + 1;
            countValueFormatter = this.countValueFormatter(decimals, this.panelCtrl.scaledDecimals + 2);
            bucketBoundFormatter = this.panelCtrl.tickValueFormatter(decimals, this.panelCtrl.scaledDecimals + 2);
        }
        var tooltipHtml = "<div class=\"graph-tooltip-time\">" + time + "</div>\n      <div class=\"heatmap-histogram\"></div>";
        if (yData) {
            if (yData.bounds) {
                if (data.tsBuckets) {
                    // Use Y-axis labels
                    var tickFormatter = function (valIndex) {
                        return data.tsBucketsFormatted ? data.tsBucketsFormatted[valIndex] : data.tsBuckets[valIndex];
                    };
                    boundBottom = tickFormatter(yBucketIndex);
                    if (this.panel.yBucketBound !== 'middle') {
                        boundTop = yBucketIndex < data.tsBuckets.length - 1 ? tickFormatter(yBucketIndex + 1) : '';
                    }
                }
                else {
                    // Display 0 if bucket is a special 'zero' bucket
                    var bottom = yData.y ? yData.bounds.bottom : 0;
                    boundBottom = bucketBoundFormatter(bottom);
                    boundTop = bucketBoundFormatter(yData.bounds.top);
                }
                valuesNumber = countValueFormatter(yData.count);
                var boundStr = boundTop && boundBottom ? boundBottom + " - " + boundTop : boundBottom || boundTop;
                tooltipHtml += "<div>\n          bucket: <b>" + boundStr + "</b> <br>\n          count: <b>" + valuesNumber + "</b> <br>\n        </div>";
            }
            else {
                // currently no bounds for pre bucketed data
                tooltipHtml += "<div>count: <b>" + yData.count + "</b><br></div>";
            }
        }
        else {
            if (!this.panel.tooltip.showHistogram) {
                this.destroy();
                return;
            }
            boundBottom = yBucketIndex;
            boundTop = '';
            valuesNumber = 0;
        }
        this.tooltip.html(tooltipHtml);
        if (this.panel.tooltip.showHistogram) {
            this.addHistogram(xData);
        }
        this.move(pos);
    };
    HeatmapTooltip.prototype.getBucketIndexes = function (pos, data) {
        var xBucketIndex = this.getXBucketIndex(pos.x, data);
        var yBucketIndex = this.getYBucketIndex(pos.y, data);
        return { xBucketIndex: xBucketIndex, yBucketIndex: yBucketIndex };
    };
    HeatmapTooltip.prototype.getXBucketIndex = function (x, data) {
        // First try to find X bucket by checking x pos is in the
        // [bucket.x, bucket.x + xBucketSize] interval
        var xBucket = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.find(data.buckets, function (bucket) {
            return x > bucket.x && x - bucket.x <= data.xBucketSize;
        });
        return xBucket ? xBucket.x : Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_3__["getValueBucketBound"])(x, data.xBucketSize, 1);
    };
    HeatmapTooltip.prototype.getYBucketIndex = function (y, data) {
        if (data.tsBuckets) {
            return Math.floor(y);
        }
        var yBucketIndex = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_3__["getValueBucketBound"])(y, data.yBucketSize, this.panel.yAxis.logBase);
        return yBucketIndex;
    };
    HeatmapTooltip.prototype.getSharedTooltipPos = function (pos) {
        // get pageX from position on x axis and pageY from relative position in original panel
        pos.pageX = this.heatmapPanel.offset().left + this.scope.xScale(pos.x);
        pos.pageY = this.heatmapPanel.offset().top + this.scope.chartHeight * pos.panelRelY;
        return pos;
    };
    HeatmapTooltip.prototype.addHistogram = function (data) {
        var xBucket = this.scope.ctrl.data.buckets[data.x];
        var yBucketSize = this.scope.ctrl.data.yBucketSize;
        var min, max, ticks;
        if (this.scope.ctrl.data.tsBuckets) {
            min = 0;
            max = this.scope.ctrl.data.tsBuckets.length - 1;
            ticks = this.scope.ctrl.data.tsBuckets.length;
        }
        else {
            min = this.scope.ctrl.data.yAxis.min;
            max = this.scope.ctrl.data.yAxis.max;
            ticks = this.scope.ctrl.data.yAxis.ticks;
        }
        var histogramData = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(xBucket.buckets, function (bucket) {
            var count = bucket.count !== undefined ? bucket.count : bucket.values.length;
            return [bucket.bounds.bottom, count];
        });
        histogramData = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.filter(histogramData, function (d) {
            return d[0] >= min && d[0] <= max;
        });
        var scale = this.scope.yScale.copy();
        var histXScale = scale.domain([min, max]).range([0, HISTOGRAM_WIDTH]);
        var barWidth;
        if (this.panel.yAxis.logBase === 1) {
            barWidth = Math.floor((HISTOGRAM_WIDTH / (max - min)) * yBucketSize * 0.9);
        }
        else {
            var barNumberFactor = yBucketSize ? yBucketSize : 1;
            barWidth = Math.floor((HISTOGRAM_WIDTH / ticks / barNumberFactor) * 0.9);
        }
        barWidth = Math.max(barWidth, 1);
        // Normalize histogram Y axis
        var histogramDomain = lodash__WEBPACK_IMPORTED_MODULE_2___default.a.reduce(lodash__WEBPACK_IMPORTED_MODULE_2___default.a.map(histogramData, function (d) { return d[1]; }), function (sum, val) { return sum + val; }, 0);
        var histYScale = d3__WEBPACK_IMPORTED_MODULE_0__["scaleLinear"]()
            .domain([0, histogramDomain])
            .range([0, HISTOGRAM_HEIGHT]);
        var histogram = this.tooltip
            .select('.heatmap-histogram')
            .append('svg')
            .attr('width', HISTOGRAM_WIDTH)
            .attr('height', HISTOGRAM_HEIGHT);
        histogram
            .selectAll('.bar')
            .data(histogramData)
            .enter()
            .append('rect')
            .attr('x', function (d) {
            return histXScale(d[0]);
        })
            .attr('width', barWidth)
            .attr('y', function (d) {
            return HISTOGRAM_HEIGHT - histYScale(d[1]);
        })
            .attr('height', function (d) {
            return histYScale(d[1]);
        });
    };
    HeatmapTooltip.prototype.move = function (pos) {
        if (!this.tooltip) {
            return;
        }
        var elem = jquery__WEBPACK_IMPORTED_MODULE_1___default()(this.tooltip.node())[0];
        var tooltipWidth = elem.clientWidth;
        var tooltipHeight = elem.clientHeight;
        var left = pos.pageX + TOOLTIP_PADDING_X;
        var top = pos.pageY + TOOLTIP_PADDING_Y;
        if (pos.pageX + tooltipWidth + 40 > window.innerWidth) {
            left = pos.pageX - tooltipWidth - TOOLTIP_PADDING_X;
        }
        if (pos.pageY - window.pageYOffset + tooltipHeight + 20 > window.innerHeight) {
            top = pos.pageY - tooltipHeight - TOOLTIP_PADDING_Y;
        }
        return this.tooltip.style('left', left + 'px').style('top', top + 'px');
    };
    HeatmapTooltip.prototype.countValueFormatter = function (decimals, scaledDecimals) {
        if (scaledDecimals === void 0) { scaledDecimals = null; }
        var format = 'short';
        return function (value) {
            return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_4__["getValueFormat"])(format)(value, decimals, scaledDecimals);
        };
    };
    return HeatmapTooltip;
}());



/***/ }),

/***/ "./public/app/plugins/panel/heatmap/module.ts":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/module.ts ***!
  \****************************************************/
/*! exports provided: PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _color_legend__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./color_legend */ "./public/app/plugins/panel/heatmap/color_legend.ts");
/* harmony import */ var _heatmap_ctrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./heatmap_ctrl */ "./public/app/plugins/panel/heatmap/heatmap_ctrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return _heatmap_ctrl__WEBPACK_IMPORTED_MODULE_1__["HeatmapCtrl"]; });






/***/ }),

/***/ "./public/app/plugins/panel/heatmap/rendering.ts":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/heatmap/rendering.ts ***!
  \*******************************************************/
/*! exports provided: default, HeatmapRenderer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return rendering; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HeatmapRenderer", function() { return HeatmapRenderer; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! d3 */ "./node_modules/d3/index.js");
/* harmony import */ var app_core_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/core */ "./public/app/core/core.ts");
/* harmony import */ var app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/ticks */ "./public/app/core/utils/ticks.ts");
/* harmony import */ var _heatmap_tooltip__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./heatmap_tooltip */ "./public/app/plugins/panel/heatmap/heatmap_tooltip.ts");
/* harmony import */ var _heatmap_data_converter__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./heatmap_data_converter */ "./public/app/plugins/panel/heatmap/heatmap_data_converter.ts");
/* harmony import */ var _color_scale__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./color_scale */ "./public/app/plugins/panel/heatmap/color_scale.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");










var MIN_CARD_SIZE = 1, CARD_PADDING = 1, CARD_ROUND = 0, DATA_RANGE_WIDING_FACTOR = 1.2, DEFAULT_X_TICK_SIZE_PX = 100, DEFAULT_Y_TICK_SIZE_PX = 50, X_AXIS_TICK_PADDING = 10, Y_AXIS_TICK_PADDING = 5, MIN_SELECTION_WIDTH = 2;
function rendering(scope, elem, attrs, ctrl) {
    return new HeatmapRenderer(scope, elem, attrs, ctrl);
}
var HeatmapRenderer = /** @class */ (function () {
    function HeatmapRenderer(scope, elem, attrs, ctrl) {
        this.scope = scope;
        this.elem = elem;
        this.ctrl = ctrl;
        // $heatmap is JQuery object, but heatmap is D3
        this.$heatmap = this.elem.find('.heatmap-panel');
        this.tooltip = new _heatmap_tooltip__WEBPACK_IMPORTED_MODULE_5__["HeatmapTooltip"](this.$heatmap, this.scope);
        this.selection = {
            active: false,
            x1: -1,
            x2: -1,
        };
        this.padding = { left: 0, right: 0, top: 0, bottom: 0 };
        this.margin = { left: 25, right: 15, top: 10, bottom: 20 };
        this.dataRangeWidingFactor = DATA_RANGE_WIDING_FACTOR;
        this.ctrl.events.on('render', this.onRender.bind(this));
        this.ctrl.tickValueFormatter = this.tickValueFormatter.bind(this);
        /////////////////////////////
        // Selection and crosshair //
        /////////////////////////////
        // Shared crosshair and tooltip
        app_core_core__WEBPACK_IMPORTED_MODULE_3__["appEvents"].on('graph-hover', this.onGraphHover.bind(this), this.scope);
        app_core_core__WEBPACK_IMPORTED_MODULE_3__["appEvents"].on('graph-hover-clear', this.onGraphHoverClear.bind(this), this.scope);
        // Register selection listeners
        this.$heatmap.on('mousedown', this.onMouseDown.bind(this));
        this.$heatmap.on('mousemove', this.onMouseMove.bind(this));
        this.$heatmap.on('mouseleave', this.onMouseLeave.bind(this));
    }
    HeatmapRenderer.prototype.onGraphHoverClear = function () {
        this.clearCrosshair();
    };
    HeatmapRenderer.prototype.onGraphHover = function (event) {
        this.drawSharedCrosshair(event.pos);
    };
    HeatmapRenderer.prototype.onRender = function () {
        this.render();
        this.ctrl.renderingCompleted();
    };
    HeatmapRenderer.prototype.setElementHeight = function () {
        try {
            var height = this.ctrl.height || this.panel.height || this.ctrl.row.height;
            if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(height)) {
                height = parseInt(height.replace('px', ''), 10);
            }
            height -= this.panel.legend.show ? 28 : 11; // bottom padding and space for legend
            this.$heatmap.css('height', height + 'px');
            return true;
        }
        catch (e) {
            // IE throws errors sometimes
            return false;
        }
    };
    HeatmapRenderer.prototype.getYAxisWidth = function (elem) {
        var axisText = elem.selectAll('.axis-y text').nodes();
        var maxTextWidth = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.max(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(axisText, function (text) {
            // Use SVG getBBox method
            return text.getBBox().width;
        }));
        return maxTextWidth;
    };
    HeatmapRenderer.prototype.getXAxisHeight = function (elem) {
        var axisLine = elem.select('.axis-x line');
        if (!axisLine.empty()) {
            var axisLinePosition = parseFloat(elem.select('.axis-x line').attr('y2'));
            var canvasWidth = parseFloat(elem.attr('height'));
            return canvasWidth - axisLinePosition;
        }
        else {
            // Default height
            return 30;
        }
    };
    HeatmapRenderer.prototype.addXAxis = function () {
        this.scope.xScale = this.xScale = d3__WEBPACK_IMPORTED_MODULE_2__["scaleTime"]()
            .domain([this.timeRange.from, this.timeRange.to])
            .range([0, this.chartWidth]);
        var ticks = this.chartWidth / DEFAULT_X_TICK_SIZE_PX;
        var grafanaTimeFormatter = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["grafanaTimeFormat"](ticks, this.timeRange.from, this.timeRange.to);
        var timeFormat;
        var dashboardTimeZone = this.ctrl.dashboard.getTimezone();
        if (dashboardTimeZone === 'utc') {
            timeFormat = d3__WEBPACK_IMPORTED_MODULE_2__["utcFormat"](grafanaTimeFormatter);
        }
        else {
            timeFormat = d3__WEBPACK_IMPORTED_MODULE_2__["timeFormat"](grafanaTimeFormatter);
        }
        var xAxis = d3__WEBPACK_IMPORTED_MODULE_2__["axisBottom"](this.xScale)
            .ticks(ticks)
            .tickFormat(timeFormat)
            .tickPadding(X_AXIS_TICK_PADDING)
            .tickSize(this.chartHeight);
        var posY = this.margin.top;
        var posX = this.yAxisWidth;
        this.heatmap
            .append('g')
            .attr('class', 'axis axis-x')
            .attr('transform', 'translate(' + posX + ',' + posY + ')')
            .call(xAxis);
        // Remove horizontal line in the top of axis labels (called domain in d3)
        this.heatmap
            .select('.axis-x')
            .select('.domain')
            .remove();
    };
    HeatmapRenderer.prototype.addYAxis = function () {
        var ticks = Math.ceil(this.chartHeight / DEFAULT_Y_TICK_SIZE_PX);
        var tickInterval = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["tickStep"](this.data.heatmapStats.min, this.data.heatmapStats.max, ticks);
        var _a = this.wideYAxisRange(this.data.heatmapStats.min, this.data.heatmapStats.max, tickInterval), yMin = _a.yMin, yMax = _a.yMax;
        // Rewrite min and max if it have been set explicitly
        yMin = this.panel.yAxis.min !== null ? this.panel.yAxis.min : yMin;
        yMax = this.panel.yAxis.max !== null ? this.panel.yAxis.max : yMax;
        // Adjust ticks after Y range widening
        tickInterval = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["tickStep"](yMin, yMax, ticks);
        ticks = Math.ceil((yMax - yMin) / tickInterval);
        var decimalsAuto = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getPrecision"](tickInterval);
        var decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals;
        // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
        var flotTickSize = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getFlotTickSize"](yMin, yMax, ticks, decimalsAuto);
        var scaledDecimals = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getScaledDecimals"](decimals, flotTickSize);
        this.ctrl.decimals = decimals;
        this.ctrl.scaledDecimals = scaledDecimals;
        // Set default Y min and max if no data
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isEmpty(this.data.buckets)) {
            yMax = 1;
            yMin = -1;
            ticks = 3;
            decimals = 1;
        }
        this.data.yAxis = {
            min: yMin,
            max: yMax,
            ticks: ticks,
        };
        this.scope.yScale = this.yScale = d3__WEBPACK_IMPORTED_MODULE_2__["scaleLinear"]()
            .domain([yMin, yMax])
            .range([this.chartHeight, 0]);
        var yAxis = d3__WEBPACK_IMPORTED_MODULE_2__["axisLeft"](this.yScale)
            .ticks(ticks)
            .tickFormat(this.tickValueFormatter(decimals, scaledDecimals))
            .tickSizeInner(0 - this.width)
            .tickSizeOuter(0)
            .tickPadding(Y_AXIS_TICK_PADDING);
        this.heatmap
            .append('g')
            .attr('class', 'axis axis-y')
            .call(yAxis);
        // Calculate Y axis width first, then move axis into visible area
        var posY = this.margin.top;
        var posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
        this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
        // Remove vertical line in the right of axis labels (called domain in d3)
        this.heatmap
            .select('.axis-y')
            .select('.domain')
            .remove();
    };
    // Wide Y values range and anjust to bucket size
    HeatmapRenderer.prototype.wideYAxisRange = function (min, max, tickInterval) {
        var yWiding = (max * (this.dataRangeWidingFactor - 1) - min * (this.dataRangeWidingFactor - 1)) / 2;
        var yMin, yMax;
        if (tickInterval === 0) {
            yMax = max * this.dataRangeWidingFactor;
            yMin = min - min * (this.dataRangeWidingFactor - 1);
        }
        else {
            yMax = Math.ceil((max + yWiding) / tickInterval) * tickInterval;
            yMin = Math.floor((min - yWiding) / tickInterval) * tickInterval;
        }
        // Don't wide axis below 0 if all values are positive
        if (min >= 0 && yMin < 0) {
            yMin = 0;
        }
        return { yMin: yMin, yMax: yMax };
    };
    HeatmapRenderer.prototype.addLogYAxis = function () {
        var logBase = this.panel.yAxis.logBase;
        var _a = this.adjustLogRange(this.data.heatmapStats.minLog, this.data.heatmapStats.max, logBase), yMin = _a.yMin, yMax = _a.yMax;
        yMin =
            this.panel.yAxis.min && this.panel.yAxis.min !== '0' ? this.adjustLogMin(this.panel.yAxis.min, logBase) : yMin;
        yMax = this.panel.yAxis.max !== null ? this.adjustLogMax(this.panel.yAxis.max, logBase) : yMax;
        // Set default Y min and max if no data
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isEmpty(this.data.buckets)) {
            yMax = Math.pow(logBase, 2);
            yMin = 1;
        }
        this.scope.yScale = this.yScale = d3__WEBPACK_IMPORTED_MODULE_2__["scaleLog"]()
            .base(this.panel.yAxis.logBase)
            .domain([yMin, yMax])
            .range([this.chartHeight, 0]);
        var domain = this.yScale.domain();
        var tickValues = this.logScaleTickValues(domain, logBase);
        var decimalsAuto = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getPrecision"](yMin);
        var decimals = this.panel.yAxis.decimals || decimalsAuto;
        // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js)
        var flotTickSize = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getFlotTickSize"](yMin, yMax, tickValues.length, decimalsAuto);
        var scaledDecimals = app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getScaledDecimals"](decimals, flotTickSize);
        this.ctrl.decimals = decimals;
        this.ctrl.scaledDecimals = scaledDecimals;
        this.data.yAxis = {
            min: yMin,
            max: yMax,
            ticks: tickValues.length,
        };
        var yAxis = d3__WEBPACK_IMPORTED_MODULE_2__["axisLeft"](this.yScale)
            .tickValues(tickValues)
            .tickFormat(this.tickValueFormatter(decimals, scaledDecimals))
            .tickSizeInner(0 - this.width)
            .tickSizeOuter(0)
            .tickPadding(Y_AXIS_TICK_PADDING);
        this.heatmap
            .append('g')
            .attr('class', 'axis axis-y')
            .call(yAxis);
        // Calculate Y axis width first, then move axis into visible area
        var posY = this.margin.top;
        var posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
        this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
        // Set first tick as pseudo 0
        if (yMin < 1) {
            this.heatmap
                .select('.axis-y')
                .select('.tick text')
                .text('0');
        }
        // Remove vertical line in the right of axis labels (called domain in d3)
        this.heatmap
            .select('.axis-y')
            .select('.domain')
            .remove();
    };
    HeatmapRenderer.prototype.addYAxisFromBuckets = function () {
        var tsBuckets = this.data.tsBuckets;
        this.scope.yScale = this.yScale = d3__WEBPACK_IMPORTED_MODULE_2__["scaleLinear"]()
            .domain([0, tsBuckets.length - 1])
            .range([this.chartHeight, 0]);
        var tickValues = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(tsBuckets, function (b, i) { return i; });
        var decimalsAuto = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.max(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(tsBuckets, app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["getStringPrecision"]));
        var decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals;
        this.ctrl.decimals = decimals;
        var tickValueFormatter = this.tickValueFormatter.bind(this);
        function tickFormatter(valIndex) {
            var valueFormatted = tsBuckets[valIndex];
            if (!lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNaN(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.toNumber(valueFormatted)) && valueFormatted !== '') {
                // Try to format numeric tick labels
                valueFormatted = tickValueFormatter(decimals)(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.toNumber(valueFormatted));
            }
            return valueFormatted;
        }
        var tsBucketsFormatted = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(tsBuckets, function (v, i) { return tickFormatter(i); });
        this.data.tsBucketsFormatted = tsBucketsFormatted;
        var yAxis = d3__WEBPACK_IMPORTED_MODULE_2__["axisLeft"](this.yScale)
            .tickValues(tickValues)
            .tickFormat(tickFormatter)
            .tickSizeInner(0 - this.width)
            .tickSizeOuter(0)
            .tickPadding(Y_AXIS_TICK_PADDING);
        this.heatmap
            .append('g')
            .attr('class', 'axis axis-y')
            .call(yAxis);
        // Calculate Y axis width first, then move axis into visible area
        var posY = this.margin.top;
        var posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
        this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')');
        if (this.panel.yBucketBound === 'middle' && tickValues && tickValues.length) {
            // Shift Y axis labels to the middle of bucket
            var tickShift = 0 - this.chartHeight / (tickValues.length - 1) / 2;
            this.heatmap.selectAll('.axis-y text').attr('transform', 'translate(' + 0 + ',' + tickShift + ')');
        }
        // Remove vertical line in the right of axis labels (called domain in d3)
        this.heatmap
            .select('.axis-y')
            .select('.domain')
            .remove();
    };
    // Adjust data range to log base
    HeatmapRenderer.prototype.adjustLogRange = function (min, max, logBase) {
        var yMin = this.data.heatmapStats.minLog;
        if (this.data.heatmapStats.minLog > 1 || !this.data.heatmapStats.minLog) {
            yMin = 1;
        }
        else {
            yMin = this.adjustLogMin(this.data.heatmapStats.minLog, logBase);
        }
        // Adjust max Y value to log base
        var yMax = this.adjustLogMax(this.data.heatmapStats.max, logBase);
        return { yMin: yMin, yMax: yMax };
    };
    HeatmapRenderer.prototype.adjustLogMax = function (max, base) {
        return Math.pow(base, Math.ceil(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["logp"](max, base)));
    };
    HeatmapRenderer.prototype.adjustLogMin = function (min, base) {
        return Math.pow(base, Math.floor(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["logp"](min, base)));
    };
    HeatmapRenderer.prototype.logScaleTickValues = function (domain, base) {
        var domainMin = domain[0];
        var domainMax = domain[1];
        var tickValues = [];
        if (domainMin < 1) {
            var underOneTicks = Math.floor(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["logp"](domainMin, base));
            for (var i = underOneTicks; i < 0; i++) {
                var tickValue = Math.pow(base, i);
                tickValues.push(tickValue);
            }
        }
        var ticks = Math.ceil(app_core_utils_ticks__WEBPACK_IMPORTED_MODULE_4__["logp"](domainMax, base));
        for (var i = 0; i <= ticks; i++) {
            var tickValue = Math.pow(base, i);
            tickValues.push(tickValue);
        }
        return tickValues;
    };
    HeatmapRenderer.prototype.tickValueFormatter = function (decimals, scaledDecimals) {
        if (scaledDecimals === void 0) { scaledDecimals = null; }
        var format = this.panel.yAxis.format;
        return function (value) {
            try {
                return format !== 'none' ? Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_8__["getValueFormat"])(format)(value, decimals, scaledDecimals) : value;
            }
            catch (err) {
                console.error(err.message || err);
                return value;
            }
        };
    };
    HeatmapRenderer.prototype.fixYAxisTickSize = function () {
        this.heatmap
            .select('.axis-y')
            .selectAll('.tick line')
            .attr('x2', this.chartWidth);
    };
    HeatmapRenderer.prototype.addAxes = function () {
        this.chartHeight = this.height - this.margin.top - this.margin.bottom;
        this.chartTop = this.margin.top;
        this.chartBottom = this.chartTop + this.chartHeight;
        if (this.panel.dataFormat === 'tsbuckets') {
            this.addYAxisFromBuckets();
        }
        else {
            if (this.panel.yAxis.logBase === 1) {
                this.addYAxis();
            }
            else {
                this.addLogYAxis();
            }
        }
        this.yAxisWidth = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING;
        this.chartWidth = this.width - this.yAxisWidth - this.margin.right;
        this.fixYAxisTickSize();
        this.addXAxis();
        this.xAxisHeight = this.getXAxisHeight(this.heatmap);
        if (!this.panel.yAxis.show) {
            this.heatmap
                .select('.axis-y')
                .selectAll('line')
                .style('opacity', 0);
        }
        if (!this.panel.xAxis.show) {
            this.heatmap
                .select('.axis-x')
                .selectAll('line')
                .style('opacity', 0);
        }
    };
    HeatmapRenderer.prototype.addHeatmapCanvas = function () {
        var heatmapElem = this.$heatmap[0];
        this.width = Math.floor(this.$heatmap.width()) - this.padding.right;
        this.height = Math.floor(this.$heatmap.height()) - this.padding.bottom;
        this.cardPadding = this.panel.cards.cardPadding !== null ? this.panel.cards.cardPadding : CARD_PADDING;
        this.cardRound = this.panel.cards.cardRound !== null ? this.panel.cards.cardRound : CARD_ROUND;
        if (this.heatmap) {
            this.heatmap.remove();
        }
        this.heatmap = d3__WEBPACK_IMPORTED_MODULE_2__["select"](heatmapElem)
            .append('svg')
            .attr('width', this.width)
            .attr('height', this.height);
    };
    HeatmapRenderer.prototype.addHeatmap = function () {
        var _this = this;
        this.addHeatmapCanvas();
        this.addAxes();
        if (this.panel.yAxis.logBase !== 1 && this.panel.dataFormat !== 'tsbuckets') {
            var logBase = this.panel.yAxis.logBase;
            var domain = this.yScale.domain();
            var tickValues = this.logScaleTickValues(domain, logBase);
            this.data.buckets = Object(_heatmap_data_converter__WEBPACK_IMPORTED_MODULE_6__["mergeZeroBuckets"])(this.data.buckets, lodash__WEBPACK_IMPORTED_MODULE_0___default.a.min(tickValues));
        }
        var cardsData = this.data.cards;
        var cardStats = this.data.cardStats;
        var maxValueAuto = cardStats.max;
        var minValueAuto = Math.min(cardStats.min, 0);
        var maxValue = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNil(this.panel.color.max) ? maxValueAuto : this.panel.color.max;
        var minValue = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isNil(this.panel.color.min) ? minValueAuto : this.panel.color.min;
        var colorScheme = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(this.ctrl.colorSchemes, {
            value: this.panel.color.colorScheme,
        });
        this.colorScale = Object(_color_scale__WEBPACK_IMPORTED_MODULE_7__["getColorScale"])(colorScheme, app_core_core__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].user.lightTheme, maxValue, minValue);
        this.opacityScale = Object(_color_scale__WEBPACK_IMPORTED_MODULE_7__["getOpacityScale"])(this.panel.color, maxValue, minValue);
        this.setCardSize();
        var cards = this.heatmap.selectAll('.heatmap-card').data(cardsData);
        cards.append('title');
        cards = cards
            .enter()
            .append('rect')
            .attr('x', this.getCardX.bind(this))
            .attr('width', this.getCardWidth.bind(this))
            .attr('y', this.getCardY.bind(this))
            .attr('height', this.getCardHeight.bind(this))
            .attr('rx', this.cardRound)
            .attr('ry', this.cardRound)
            .attr('class', 'bordered heatmap-card')
            .style('fill', this.getCardColor.bind(this))
            .style('stroke', this.getCardColor.bind(this))
            .style('stroke-width', 0)
            .style('opacity', this.getCardOpacity.bind(this));
        var $cards = this.$heatmap.find('.heatmap-card');
        $cards
            .on('mouseenter', function (event) {
            _this.tooltip.mouseOverBucket = true;
            _this.highlightCard(event);
        })
            .on('mouseleave', function (event) {
            _this.tooltip.mouseOverBucket = false;
            _this.resetCardHighLight(event);
        });
    };
    HeatmapRenderer.prototype.highlightCard = function (event) {
        var color = d3__WEBPACK_IMPORTED_MODULE_2__["select"](event.target).style('fill');
        var highlightColor = d3__WEBPACK_IMPORTED_MODULE_2__["color"](color).darker(2);
        var strokeColor = d3__WEBPACK_IMPORTED_MODULE_2__["color"](color).brighter(4);
        var currentCard = d3__WEBPACK_IMPORTED_MODULE_2__["select"](event.target);
        this.tooltip.originalFillColor = color;
        currentCard
            .style('fill', highlightColor.toString())
            .style('stroke', strokeColor.toString())
            .style('stroke-width', 1);
    };
    HeatmapRenderer.prototype.resetCardHighLight = function (event) {
        d3__WEBPACK_IMPORTED_MODULE_2__["select"](event.target)
            .style('fill', this.tooltip.originalFillColor)
            .style('stroke', this.tooltip.originalFillColor)
            .style('stroke-width', 0);
    };
    HeatmapRenderer.prototype.setCardSize = function () {
        var xGridSize = Math.floor(this.xScale(this.data.xBucketSize) - this.xScale(0));
        var yGridSize = Math.floor(this.yScale(this.yScale.invert(0) - this.data.yBucketSize));
        if (this.panel.yAxis.logBase !== 1) {
            var base = this.panel.yAxis.logBase;
            var splitFactor = this.data.yBucketSize || 1;
            yGridSize = Math.floor((this.yScale(1) - this.yScale(base)) / splitFactor);
        }
        var cardWidth = xGridSize - this.cardPadding * 2;
        this.cardWidth = Math.max(cardWidth, MIN_CARD_SIZE);
        this.cardHeight = yGridSize ? yGridSize - this.cardPadding * 2 : 0;
    };
    HeatmapRenderer.prototype.getCardX = function (d) {
        var x;
        if (this.xScale(d.x) < 0) {
            // Cut card left to prevent overlay
            x = this.yAxisWidth + this.cardPadding;
        }
        else {
            x = this.xScale(d.x) + this.yAxisWidth + this.cardPadding;
        }
        return x;
    };
    HeatmapRenderer.prototype.getCardWidth = function (d) {
        var w = this.cardWidth;
        if (this.xScale(d.x) < 0) {
            // Cut card left to prevent overlay
            w = this.xScale(d.x) + this.cardWidth;
        }
        else if (this.xScale(d.x) + this.cardWidth > this.chartWidth) {
            // Cut card right to prevent overlay
            w = this.chartWidth - this.xScale(d.x) - this.cardPadding;
        }
        // Card width should be MIN_CARD_SIZE at least, but cut cards shouldn't be displayed
        w = w > 0 ? Math.max(w, MIN_CARD_SIZE) : 0;
        return w;
    };
    HeatmapRenderer.prototype.getCardY = function (d) {
        var y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding;
        if (this.panel.yAxis.logBase !== 1 && d.y === 0) {
            y = this.chartBottom - this.cardHeight - this.cardPadding;
        }
        else {
            if (y < this.chartTop) {
                y = this.chartTop;
            }
        }
        return y;
    };
    HeatmapRenderer.prototype.getCardHeight = function (d) {
        var y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding;
        var h = this.cardHeight;
        if (this.panel.yAxis.logBase !== 1 && d.y === 0) {
            return this.cardHeight;
        }
        // Cut card height to prevent overlay
        if (y < this.chartTop) {
            h = this.yScale(d.y) - this.cardPadding;
        }
        else if (this.yScale(d.y) > this.chartBottom) {
            h = this.chartBottom - y;
        }
        else if (y + this.cardHeight > this.chartBottom) {
            h = this.chartBottom - y;
        }
        // Height can't be more than chart height
        h = Math.min(h, this.chartHeight);
        // Card height should be MIN_CARD_SIZE at least
        h = Math.max(h, MIN_CARD_SIZE);
        return h;
    };
    HeatmapRenderer.prototype.getCardColor = function (d) {
        if (this.panel.color.mode === 'opacity') {
            return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_8__["getColorFromHexRgbOrName"])(this.panel.color.cardColor, app_core_core__WEBPACK_IMPORTED_MODULE_3__["contextSrv"].user.lightTheme ? _grafana_ui__WEBPACK_IMPORTED_MODULE_8__["GrafanaThemeType"].Light : _grafana_ui__WEBPACK_IMPORTED_MODULE_8__["GrafanaThemeType"].Dark);
        }
        else {
            return this.colorScale(d.count);
        }
    };
    HeatmapRenderer.prototype.getCardOpacity = function (d) {
        if (this.panel.color.mode === 'opacity') {
            return this.opacityScale(d.count);
        }
        else {
            return 1;
        }
    };
    HeatmapRenderer.prototype.getEventOffset = function (event) {
        var elemOffset = this.$heatmap.offset();
        var x = Math.floor(event.clientX - elemOffset.left);
        var y = Math.floor(event.clientY - elemOffset.top);
        return { x: x, y: y };
    };
    HeatmapRenderer.prototype.onMouseDown = function (event) {
        var _this = this;
        var offset = this.getEventOffset(event);
        this.selection.active = true;
        this.selection.x1 = offset.x;
        this.mouseUpHandler = function () {
            _this.onMouseUp();
        };
        jquery__WEBPACK_IMPORTED_MODULE_1___default()(document).one('mouseup', this.mouseUpHandler.bind(this));
    };
    HeatmapRenderer.prototype.onMouseUp = function () {
        jquery__WEBPACK_IMPORTED_MODULE_1___default()(document).unbind('mouseup', this.mouseUpHandler.bind(this));
        this.mouseUpHandler = null;
        this.selection.active = false;
        var selectionRange = Math.abs(this.selection.x2 - this.selection.x1);
        if (this.selection.x2 >= 0 && selectionRange > MIN_SELECTION_WIDTH) {
            var timeFrom = this.xScale.invert(Math.min(this.selection.x1, this.selection.x2) - this.yAxisWidth);
            var timeTo = this.xScale.invert(Math.max(this.selection.x1, this.selection.x2) - this.yAxisWidth);
            this.ctrl.timeSrv.setTime({
                from: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_9__["toUtc"])(timeFrom),
                to: Object(_grafana_data__WEBPACK_IMPORTED_MODULE_9__["toUtc"])(timeTo),
            });
        }
        this.clearSelection();
    };
    HeatmapRenderer.prototype.onMouseLeave = function () {
        app_core_core__WEBPACK_IMPORTED_MODULE_3__["appEvents"].emit('graph-hover-clear');
        this.clearCrosshair();
    };
    HeatmapRenderer.prototype.onMouseMove = function (event) {
        if (!this.heatmap) {
            return;
        }
        var offset = this.getEventOffset(event);
        if (this.selection.active) {
            // Clear crosshair and tooltip
            this.clearCrosshair();
            this.tooltip.destroy();
            this.selection.x2 = this.limitSelection(offset.x);
            this.drawSelection(this.selection.x1, this.selection.x2);
        }
        else {
            var pos = this.getEventPos(event, offset);
            this.drawCrosshair(offset.x);
            this.tooltip.show(pos, this.data);
            this.emitGraphHoverEvent(pos);
        }
    };
    HeatmapRenderer.prototype.getEventPos = function (event, offset) {
        var x = this.xScale.invert(offset.x - this.yAxisWidth).valueOf();
        var y = this.yScale.invert(offset.y - this.chartTop);
        var pos = {
            pageX: event.pageX,
            pageY: event.pageY,
            x: x,
            x1: x,
            y: y,
            y1: y,
            panelRelY: null,
            offset: offset,
        };
        return pos;
    };
    HeatmapRenderer.prototype.emitGraphHoverEvent = function (pos) {
        // Set minimum offset to prevent showing legend from another panel
        pos.panelRelY = Math.max(pos.offset.y / this.height, 0.001);
        // broadcast to other graph panels that we are hovering
        app_core_core__WEBPACK_IMPORTED_MODULE_3__["appEvents"].emit('graph-hover', { pos: pos, panel: this.panel });
    };
    HeatmapRenderer.prototype.limitSelection = function (x2) {
        x2 = Math.max(x2, this.yAxisWidth);
        x2 = Math.min(x2, this.chartWidth + this.yAxisWidth);
        return x2;
    };
    HeatmapRenderer.prototype.drawSelection = function (posX1, posX2) {
        if (this.heatmap) {
            this.heatmap.selectAll('.heatmap-selection').remove();
            var selectionX = Math.min(posX1, posX2);
            var selectionWidth = Math.abs(posX1 - posX2);
            if (selectionWidth > MIN_SELECTION_WIDTH) {
                this.heatmap
                    .append('rect')
                    .attr('class', 'heatmap-selection')
                    .attr('x', selectionX)
                    .attr('width', selectionWidth)
                    .attr('y', this.chartTop)
                    .attr('height', this.chartHeight);
            }
        }
    };
    HeatmapRenderer.prototype.clearSelection = function () {
        this.selection.x1 = -1;
        this.selection.x2 = -1;
        if (this.heatmap) {
            this.heatmap.selectAll('.heatmap-selection').remove();
        }
    };
    HeatmapRenderer.prototype.drawCrosshair = function (position) {
        if (this.heatmap) {
            this.heatmap.selectAll('.heatmap-crosshair').remove();
            var posX = position;
            posX = Math.max(posX, this.yAxisWidth);
            posX = Math.min(posX, this.chartWidth + this.yAxisWidth);
            this.heatmap
                .append('g')
                .attr('class', 'heatmap-crosshair')
                .attr('transform', 'translate(' + posX + ',0)')
                .append('line')
                .attr('x1', 1)
                .attr('y1', this.chartTop)
                .attr('x2', 1)
                .attr('y2', this.chartBottom)
                .attr('stroke-width', 1);
        }
    };
    HeatmapRenderer.prototype.drawSharedCrosshair = function (pos) {
        if (this.heatmap && this.ctrl.dashboard.graphTooltip !== 0) {
            var posX = this.xScale(pos.x) + this.yAxisWidth;
            this.drawCrosshair(posX);
        }
    };
    HeatmapRenderer.prototype.clearCrosshair = function () {
        if (this.heatmap) {
            this.heatmap.selectAll('.heatmap-crosshair').remove();
        }
    };
    HeatmapRenderer.prototype.render = function () {
        this.data = this.ctrl.data;
        this.panel = this.ctrl.panel;
        this.timeRange = this.ctrl.range;
        if (!this.setElementHeight() || !this.data) {
            return;
        }
        // Draw default axes and return if no data
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isEmpty(this.data.buckets)) {
            this.addHeatmapCanvas();
            this.addAxes();
            return;
        }
        this.addHeatmap();
        this.scope.yAxisWidth = this.yAxisWidth;
        this.scope.xAxisHeight = this.xAxisHeight;
        this.scope.chartHeight = this.chartHeight;
        this.scope.chartWidth = this.chartWidth;
        this.scope.chartTop = this.chartTop;
    };
    return HeatmapRenderer;
}());



/***/ }),

/***/ "./public/app/plugins/panel/logs/LogsPanel.tsx":
/*!*****************************************************!*\
  !*** ./public/app/plugins/panel/logs/LogsPanel.tsx ***!
  \*****************************************************/
/*! exports provided: LogsPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogsPanel", function() { return LogsPanel; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_logs_model__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/logs_model */ "./public/app/core/logs_model.ts");
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");





var LogsPanel = function (_a) {
    var data = _a.data, timeZone = _a.timeZone, _b = _a.options, showTime = _b.showTime, sortOrder = _b.sortOrder, width = _a.width;
    if (!data) {
        return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "panel-empty" },
            react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null, "No data found in response")));
    }
    var newResults = data ? Object(app_core_logs_model__WEBPACK_IMPORTED_MODULE_3__["dataFrameToLogsModel"])(data.series, data.request.intervalMs) : null;
    var sortedNewResults = Object(app_core_utils_explore__WEBPACK_IMPORTED_MODULE_4__["sortLogsResult"])(newResults, sortOrder);
    return (react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["CustomScrollbar"], { autoHide: true },
        react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["LogRows"], { data: sortedNewResults, dedupStrategy: _grafana_data__WEBPACK_IMPORTED_MODULE_2__["LogsDedupStrategy"].none, highlighterExpressions: [], showTime: showTime, showLabels: false, timeZone: timeZone })));
};


/***/ }),

/***/ "./public/app/plugins/panel/logs/LogsPanelEditor.tsx":
/*!***********************************************************!*\
  !*** ./public/app/plugins/panel/logs/LogsPanelEditor.tsx ***!
  \***********************************************************/
/*! exports provided: LogsPanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LogsPanelEditor", function() { return LogsPanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");

// Libraries



var sortOrderOptions = [
    { value: app_core_utils_explore__WEBPACK_IMPORTED_MODULE_3__["SortOrder"].Descending, label: 'Descending' },
    { value: app_core_utils_explore__WEBPACK_IMPORTED_MODULE_3__["SortOrder"].Ascending, label: 'Ascending' },
];
var LogsPanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LogsPanelEditor, _super);
    function LogsPanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onToggleTime = function () {
            var _a = _this.props, options = _a.options, onOptionsChange = _a.onOptionsChange;
            var showTime = options.showTime;
            onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { showTime: !showTime }));
        };
        _this.onShowValuesChange = function (item) {
            var _a = _this.props, options = _a.options, onOptionsChange = _a.onOptionsChange;
            onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { sortOrder: item.value }));
        };
        return _this;
    }
    LogsPanelEditor.prototype.render = function () {
        var _a = this.props.options, showTime = _a.showTime, sortOrder = _a.sortOrder;
        var value = sortOrderOptions.filter(function (option) { return option.value === sortOrder; })[0];
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGrid"], null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Columns" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Time", labelClass: "width-10", checked: showTime, onChange: this.onToggleTime }),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], null, "Order"),
                        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { options: sortOrderOptions, value: value, onChange: this.onShowValuesChange }))))));
    };
    return LogsPanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/logs/module.tsx":
/*!**************************************************!*\
  !*** ./public/app/plugins/panel/logs/module.tsx ***!
  \**************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/logs/types.ts");
/* harmony import */ var _LogsPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./LogsPanel */ "./public/app/plugins/panel/logs/LogsPanel.tsx");
/* harmony import */ var _LogsPanelEditor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LogsPanelEditor */ "./public/app/plugins/panel/logs/LogsPanelEditor.tsx");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_LogsPanel__WEBPACK_IMPORTED_MODULE_2__["LogsPanel"]).setDefaults(_types__WEBPACK_IMPORTED_MODULE_1__["defaults"]).setEditor(_LogsPanelEditor__WEBPACK_IMPORTED_MODULE_3__["LogsPanelEditor"]);


/***/ }),

/***/ "./public/app/plugins/panel/logs/types.ts":
/*!************************************************!*\
  !*** ./public/app/plugins/panel/logs/types.ts ***!
  \************************************************/
/*! exports provided: defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
/* harmony import */ var app_core_utils_explore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/utils/explore */ "./public/app/core/utils/explore.ts");

var defaults = {
    showTime: true,
    sortOrder: app_core_utils_explore__WEBPACK_IMPORTED_MODULE_0__["SortOrder"].Descending,
};


/***/ }),

/***/ "./public/app/plugins/panel/piechart/PieChartOptionsBox.tsx":
/*!******************************************************************!*\
  !*** ./public/app/plugins/panel/piechart/PieChartOptionsBox.tsx ***!
  \******************************************************************/
/*! exports provided: PieChartOptionsBox */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PieChartOptionsBox", function() { return PieChartOptionsBox; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Components

// Types


var labelWidth = 8;
var pieChartOptions = [{ value: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PieChartType"].PIE, label: 'Pie' }, { value: _grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PieChartType"].DONUT, label: 'Donut' }];
var PieChartOptionsBox = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PieChartOptionsBox, _super);
    function PieChartOptionsBox() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onPieTypeChange = function (pieType) { return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { pieType: pieType.value })); };
        _this.onStrokeWidthChange = function (_a) {
            var target = _a.target;
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { strokeWidth: target.value }));
        };
        return _this;
    }
    PieChartOptionsBox.prototype.render = function () {
        var options = this.props.options;
        var pieType = options.pieType, strokeWidth = options.strokeWidth;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "PieChart" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Type"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { width: 12, options: pieChartOptions, onChange: this.onPieTypeChange, value: pieChartOptions.find(function (option) { return option.value === pieType; }) })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Divider width", labelWidth: labelWidth, onChange: this.onStrokeWidthChange, value: strokeWidth }))));
    };
    return PieChartOptionsBox;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/piechart/PieChartPanel.tsx":
/*!*************************************************************!*\
  !*** ./public/app/plugins/panel/piechart/PieChartPanel.tsx ***!
  \*************************************************************/
/*! exports provided: PieChartPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PieChartPanel", function() { return PieChartPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Services & Utils

// Components

var PieChartPanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PieChartPanel, _super);
    function PieChartPanel() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PieChartPanel.prototype.render = function () {
        var _a = this.props, width = _a.width, height = _a.height, options = _a.options, data = _a.data, replaceVariables = _a.replaceVariables;
        var values = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getFieldDisplayValues"])({
            fieldOptions: options.fieldOptions,
            data: data.series,
            theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme,
            replaceVariables: replaceVariables,
        }).map(function (v) { return v.display; });
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["PieChart"], { width: width, height: height, values: values, pieType: options.pieType, strokeWidth: options.strokeWidth, theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme }));
    };
    return PieChartPanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/piechart/PieChartPanelEditor.tsx":
/*!*******************************************************************!*\
  !*** ./public/app/plugins/panel/piechart/PieChartPanelEditor.tsx ***!
  \*******************************************************************/
/*! exports provided: PieChartPanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PieChartPanelEditor", function() { return PieChartPanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _PieChartOptionsBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./PieChartOptionsBox */ "./public/app/plugins/panel/piechart/PieChartOptionsBox.tsx");




var PieChartPanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PieChartPanelEditor, _super);
    function PieChartPanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onValueMappingsChanged = function (mappings) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { mappings: mappings }));
        };
        _this.onDisplayOptionsChanged = function (fieldOptions) {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { fieldOptions: fieldOptions }));
        };
        _this.onDefaultsChange = function (field) {
            _this.onDisplayOptionsChanged(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions, { defaults: field }));
        };
        return _this;
    }
    PieChartPanelEditor.prototype.render = function () {
        var _a = this.props, onOptionsChange = _a.onOptionsChange, options = _a.options, data = _a.data;
        var fieldOptions = options.fieldOptions;
        var defaults = fieldOptions.defaults;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGrid"], null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Display" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldDisplayEditor"], { onChange: this.onDisplayOptionsChanged, value: fieldOptions })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Field (default)" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldPropertiesEditor"], { showMinMax: true, onChange: this.onDefaultsChange, value: defaults })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_PieChartOptionsBox__WEBPACK_IMPORTED_MODULE_3__["PieChartOptionsBox"], { data: data, onOptionsChange: onOptionsChange, options: options })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ValueMappingsEditor"], { onChange: this.onValueMappingsChanged, valueMappings: defaults.mappings })));
    };
    return PieChartPanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/piechart/module.tsx":
/*!******************************************************!*\
  !*** ./public/app/plugins/panel/piechart/module.tsx ***!
  \******************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _PieChartPanelEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./PieChartPanelEditor */ "./public/app/plugins/panel/piechart/PieChartPanelEditor.tsx");
/* harmony import */ var _PieChartPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./PieChartPanel */ "./public/app/plugins/panel/piechart/PieChartPanel.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/piechart/types.ts");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_PieChartPanel__WEBPACK_IMPORTED_MODULE_2__["PieChartPanel"])
    .setDefaults(_types__WEBPACK_IMPORTED_MODULE_3__["defaults"])
    .setEditor(_PieChartPanelEditor__WEBPACK_IMPORTED_MODULE_1__["PieChartPanelEditor"]);


/***/ }),

/***/ "./public/app/plugins/panel/piechart/types.ts":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/piechart/types.ts ***!
  \****************************************************/
/*! exports provided: defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _singlestat2_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../singlestat2/types */ "./public/app/plugins/panel/singlestat2/types.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




var defaults = {
    pieType: _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["PieChartType"].PIE,
    strokeWidth: 1,
    orientation: _grafana_ui__WEBPACK_IMPORTED_MODULE_1__["VizOrientation"].Auto,
    fieldOptions: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _singlestat2_types__WEBPACK_IMPORTED_MODULE_2__["standardFieldDisplayOptions"], { calcs: [_grafana_data__WEBPACK_IMPORTED_MODULE_3__["ReducerID"].last], defaults: {
            unit: 'short',
        } }),
};


/***/ }),

/***/ "./public/app/plugins/panel/pluginlist/module.ts":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/pluginlist/module.ts ***!
  \*******************************************************/
/*! exports provided: PluginListCtrl, PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginListCtrl", function() { return PluginListCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return PluginListCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _features_panel_panel_ctrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../features/panel/panel_ctrl */ "./public/app/features/panel/panel_ctrl.ts");



var PluginListCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PluginListCtrl, _super);
    /** @ngInject */
    function PluginListCtrl($scope, $injector, backendSrv, contextSrv) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.backendSrv = backendSrv;
        // Set and populate defaults
        _this.panelDefaults = {};
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.panel, _this.panelDefaults);
        _this.isAdmin = contextSrv.hasRole('Admin');
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.pluginList = [];
        _this.viewModel = [
            { header: 'Installed Apps', list: [], type: 'app' },
            { header: 'Installed Panels', list: [], type: 'panel' },
            { header: 'Installed Datasources', list: [], type: 'datasource' },
        ];
        _this.update();
        return _this;
    }
    PluginListCtrl.prototype.onInitEditMode = function () {
        this.addEditorTab('Options', 'public/app/plugins/panel/pluginlist/editor.html');
    };
    PluginListCtrl.prototype.gotoPlugin = function (plugin, evt) {
        if (evt) {
            evt.stopPropagation();
        }
        this.$location.url("plugins/" + plugin.id + "/edit");
    };
    PluginListCtrl.prototype.updateAvailable = function (plugin, $event) {
        $event.stopPropagation();
        $event.preventDefault();
        var modalScope = this.$scope.$new(true);
        modalScope.plugin = plugin;
        this.publishAppEvent('show-modal', {
            src: 'public/app/features/plugins/partials/update_instructions.html',
            scope: modalScope,
        });
    };
    PluginListCtrl.prototype.update = function () {
        var _this = this;
        this.backendSrv.get('api/plugins', { embedded: 0, core: 0 }).then(function (plugins) {
            var e_1, _a;
            _this.pluginList = plugins;
            _this.viewModel[0].list = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(plugins, { type: 'app' });
            _this.viewModel[1].list = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(plugins, { type: 'panel' });
            _this.viewModel[2].list = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.filter(plugins, { type: 'datasource' });
            try {
                for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](_this.pluginList), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var plugin = _c.value;
                    if (plugin.hasUpdate) {
                        plugin.state = 'has-update';
                    }
                    else if (!plugin.enabled) {
                        plugin.state = 'not-enabled';
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
        });
    };
    PluginListCtrl.templateUrl = 'module.html';
    PluginListCtrl.scrollable = true;
    return PluginListCtrl;
}(_features_panel_panel_ctrl__WEBPACK_IMPORTED_MODULE_2__["PanelCtrl"]));



/***/ }),

/***/ "./public/app/plugins/panel/singlestat/module.ts":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/singlestat/module.ts ***!
  \*******************************************************/
/*! exports provided: SingleStatCtrl, PanelCtrl, getColorForValue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SingleStatCtrl", function() { return SingleStatCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return SingleStatCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorForValue", function() { return getColorForValue; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! vendor/flot/jquery.flot */ "./public/vendor/flot/jquery.flot.js");
/* harmony import */ var vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var vendor_flot_jquery_flot_gauge__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! vendor/flot/jquery.flot.gauge */ "./public/vendor/flot/jquery.flot.gauge.js");
/* harmony import */ var vendor_flot_jquery_flot_gauge__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(vendor_flot_jquery_flot_gauge__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/panel/panellinks/link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/utils/kbn */ "./public/app/core/utils/kbn.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_features_dashboard_state_runRequest__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! app/features/dashboard/state/runRequest */ "./public/app/features/dashboard/state/runRequest.ts");












var BASE_FONT_SIZE = 38;
var SingleStatCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SingleStatCtrl, _super);
    /** @ngInject */
    function SingleStatCtrl($scope, $injector, linkSrv, $sanitize) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.linkSrv = linkSrv;
        _this.$sanitize = $sanitize;
        _this.data = {};
        _this.fieldNames = [];
        _this.valueNameOptions = [
            { value: 'min', text: 'Min' },
            { value: 'max', text: 'Max' },
            { value: 'avg', text: 'Average' },
            { value: 'current', text: 'Current' },
            { value: 'total', text: 'Total' },
            { value: 'name', text: 'Name' },
            { value: 'first', text: 'First' },
            { value: 'delta', text: 'Delta' },
            { value: 'diff', text: 'Difference' },
            { value: 'range', text: 'Range' },
            { value: 'last_time', text: 'Time of last point' },
        ];
        // Set and populate defaults
        _this.panelDefaults = {
            links: [],
            datasource: null,
            maxDataPoints: 100,
            interval: null,
            targets: [{}],
            cacheTimeout: null,
            format: 'none',
            prefix: '',
            postfix: '',
            nullText: null,
            valueMaps: [{ value: 'null', op: '=', text: 'N/A' }],
            mappingTypes: [{ name: 'value to text', value: 1 }, { name: 'range to text', value: 2 }],
            rangeMaps: [{ from: 'null', to: 'null', text: 'N/A' }],
            mappingType: 1,
            nullPointMode: 'connected',
            valueName: 'avg',
            prefixFontSize: '50%',
            valueFontSize: '80%',
            postfixFontSize: '50%',
            thresholds: '',
            colorBackground: false,
            colorValue: false,
            colors: ['#299c46', 'rgba(237, 129, 40, 0.89)', '#d44a3a'],
            sparkline: {
                show: false,
                full: false,
                ymin: null,
                ymax: null,
                lineColor: 'rgb(31, 120, 193)',
                fillColor: 'rgba(31, 118, 189, 0.18)',
            },
            gauge: {
                show: false,
                minValue: 0,
                maxValue: 100,
                thresholdMarkers: true,
                thresholdLabels: false,
            },
            tableColumn: '',
        };
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.panel, _this.panelDefaults);
        _this.events.on('data-frames-received', _this.onFramesReceived.bind(_this));
        _this.events.on('data-error', _this.onDataError.bind(_this));
        _this.events.on('data-snapshot-load', _this.onSnapshotLoad.bind(_this));
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.useDataFrames = true;
        _this.onSparklineColorChange = _this.onSparklineColorChange.bind(_this);
        _this.onSparklineFillChange = _this.onSparklineFillChange.bind(_this);
        return _this;
    }
    SingleStatCtrl.prototype.onInitEditMode = function () {
        this.fontSizes = ['20%', '30%', '50%', '70%', '80%', '100%', '110%', '120%', '150%', '170%', '200%'];
        this.addEditorTab('Options', 'public/app/plugins/panel/singlestat/editor.html', 2);
        this.addEditorTab('Value Mappings', 'public/app/plugins/panel/singlestat/mappings.html', 3);
        this.unitFormats = app_core_utils_kbn__WEBPACK_IMPORTED_MODULE_7__["default"].getUnitFormats();
    };
    SingleStatCtrl.prototype.migrateToGaugePanel = function (migrate) {
        if (migrate) {
            this.onPluginTypeChange(app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].panels['gauge']);
        }
        else {
            this.panel.gauge.show = false;
            this.render();
        }
    };
    SingleStatCtrl.prototype.setUnitFormat = function (subItem) {
        this.panel.format = subItem.value;
        this.refresh();
    };
    SingleStatCtrl.prototype.onDataError = function (err) {
        this.handleDataFrames([]);
    };
    SingleStatCtrl.prototype.onSnapshotLoad = function (dataList) {
        this.onFramesReceived(Object(app_features_dashboard_state_runRequest__WEBPACK_IMPORTED_MODULE_11__["getProcessedDataFrames"])(dataList));
    };
    SingleStatCtrl.prototype.onFramesReceived = function (frames) {
        var panel = this.panel;
        if (frames && frames.length > 1) {
            this.data = {
                value: 0,
                display: {
                    text: 'Only queries that return single series/table is supported',
                    numeric: NaN,
                },
            };
            this.render();
            return;
        }
        var distinct = getDistinctNames(frames);
        var fieldInfo = distinct.byName[panel.tableColumn]; //
        this.fieldNames = distinct.names;
        if (!fieldInfo) {
            fieldInfo = distinct.first;
        }
        if (!fieldInfo) {
            // When we don't have any field
            this.data = {
                value: 'No Data',
                display: {
                    text: 'No Data',
                    numeric: NaN,
                },
            };
        }
        else {
            this.data = this.processField(fieldInfo);
        }
        this.render();
    };
    SingleStatCtrl.prototype.processField = function (fieldInfo) {
        var _a = this, panel = _a.panel, dashboard = _a.dashboard;
        var name = fieldInfo.field.config.title || fieldInfo.field.name;
        var calc = panel.valueName;
        var calcField = fieldInfo.field;
        var val = undefined;
        if ('name' === calc) {
            val = name;
        }
        else {
            if ('last_time' === calc) {
                if (fieldInfo.frame.firstTimeField) {
                    calcField = fieldInfo.frame.firstTimeField;
                    calc = _grafana_data__WEBPACK_IMPORTED_MODULE_10__["ReducerID"].last;
                }
            }
            // Normalize functions (avg -> mean, etc)
            var r = _grafana_data__WEBPACK_IMPORTED_MODULE_10__["fieldReducers"].getIfExists(calc);
            if (r) {
                calc = r.id;
                // With strings, don't accidentally use a math function
                if (calcField.type === _grafana_data__WEBPACK_IMPORTED_MODULE_10__["FieldType"].string) {
                    var avoid = [_grafana_data__WEBPACK_IMPORTED_MODULE_10__["ReducerID"].mean, _grafana_data__WEBPACK_IMPORTED_MODULE_10__["ReducerID"].sum];
                    if (avoid.includes(calc)) {
                        calc = panel.valueName = _grafana_data__WEBPACK_IMPORTED_MODULE_10__["ReducerID"].first;
                    }
                }
            }
            else {
                calc = _grafana_data__WEBPACK_IMPORTED_MODULE_10__["ReducerID"].lastNotNull;
            }
            // Calculate the value
            val = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_10__["reduceField"])({
                field: calcField,
                reducers: [calc],
            })[calc];
        }
        var processor = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["getDisplayProcessor"])({
            config: tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, fieldInfo.field.config, { unit: panel.format, decimals: panel.decimals, mappings: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["convertOldAngulrValueMapping"])(panel) }),
            theme: app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].theme,
            isUtc: dashboard.isTimezoneUtc && dashboard.isTimezoneUtc(),
        });
        var sparkline = [];
        var data = {
            field: fieldInfo.field,
            value: val,
            display: processor(val),
            scopedVars: lodash__WEBPACK_IMPORTED_MODULE_1___default.a.extend({}, panel.scopedVars),
            sparkline: sparkline,
        };
        data.scopedVars['__name'] = { value: name };
        panel.tableColumn = this.fieldNames.length > 1 ? name : '';
        // Get the fields for a sparkline
        if (panel.sparkline && panel.sparkline.show && fieldInfo.frame.firstTimeField) {
            data.sparkline = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["getFlotPairs"])({
                xField: fieldInfo.frame.firstTimeField,
                yField: fieldInfo.field,
                nullValueMode: panel.nullPointMode,
            });
        }
        return data;
    };
    SingleStatCtrl.prototype.canModifyText = function () {
        return !this.panel.gauge.show;
    };
    SingleStatCtrl.prototype.setColoring = function (options) {
        if (options.background) {
            this.panel.colorValue = false;
            this.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
        }
        else {
            this.panel.colorBackground = false;
            this.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
        }
        this.render();
    };
    SingleStatCtrl.prototype.invertColorOrder = function () {
        var tmp = this.panel.colors[0];
        this.panel.colors[0] = this.panel.colors[2];
        this.panel.colors[2] = tmp;
        this.render();
    };
    SingleStatCtrl.prototype.onColorChange = function (panelColorIndex) {
        var _this = this;
        return function (color) {
            _this.panel.colors[panelColorIndex] = color;
            _this.render();
        };
    };
    SingleStatCtrl.prototype.onSparklineColorChange = function (newColor) {
        this.panel.sparkline.lineColor = newColor;
        this.render();
    };
    SingleStatCtrl.prototype.onSparklineFillChange = function (newColor) {
        this.panel.sparkline.fillColor = newColor;
        this.render();
    };
    SingleStatCtrl.prototype.removeValueMap = function (map) {
        var index = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.panel.valueMaps, map);
        this.panel.valueMaps.splice(index, 1);
        this.render();
    };
    SingleStatCtrl.prototype.addValueMap = function () {
        this.panel.valueMaps.push({ value: '', op: '=', text: '' });
    };
    SingleStatCtrl.prototype.removeRangeMap = function (rangeMap) {
        var index = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.indexOf(this.panel.rangeMaps, rangeMap);
        this.panel.rangeMaps.splice(index, 1);
        this.render();
    };
    SingleStatCtrl.prototype.addRangeMap = function () {
        this.panel.rangeMaps.push({ from: '', to: '', text: '' });
    };
    SingleStatCtrl.prototype.link = function (scope, elem, attrs, ctrl) {
        var $location = this.$location;
        var linkSrv = this.linkSrv;
        var $timeout = this.$timeout;
        var $sanitize = this.$sanitize;
        var panel = ctrl.panel;
        var templateSrv = this.templateSrv;
        var linkInfo = null;
        var $panelContainer = elem.find('.panel-container');
        elem = elem.find('.singlestat-panel');
        function applyColoringThresholds(valueString) {
            var data = ctrl.data;
            var color = getColorForValue(data, data.value);
            if (color) {
                return '<span style="color:' + color + '">' + valueString + '</span>';
            }
            return valueString;
        }
        function getSpan(className, fontSizePercent, applyColoring, value) {
            value = $sanitize(templateSrv.replace(value, ctrl.data.scopedVars));
            value = applyColoring ? applyColoringThresholds(value) : value;
            var pixelSize = (parseInt(fontSizePercent, 10) / 100) * BASE_FONT_SIZE;
            return '<span class="' + className + '" style="font-size:' + pixelSize + 'px">' + value + '</span>';
        }
        function getBigValueHtml() {
            var data = ctrl.data;
            var body = '<div class="singlestat-panel-value-container">';
            if (panel.prefix) {
                body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, panel.colorPrefix, panel.prefix);
            }
            body += getSpan('singlestat-panel-value', panel.valueFontSize, panel.colorValue, data.display.text);
            if (panel.postfix) {
                body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.colorPostfix, panel.postfix);
            }
            body += '</div>';
            return body;
        }
        function getValueText() {
            var data = ctrl.data;
            var result = panel.prefix ? templateSrv.replace(panel.prefix, data.scopedVars) : '';
            result += data.display.text;
            result += panel.postfix ? templateSrv.replace(panel.postfix, data.scopedVars) : '';
            return result;
        }
        function addGauge() {
            var data = ctrl.data;
            var width = elem.width();
            var height = elem.height();
            // Allow to use a bit more space for wide gauges
            var dimension = Math.min(width, height * 1.3);
            ctrl.invalidGaugeRange = false;
            if (panel.gauge.minValue > panel.gauge.maxValue) {
                ctrl.invalidGaugeRange = true;
                return;
            }
            var plotCanvas = jquery__WEBPACK_IMPORTED_MODULE_2___default()('<div></div>');
            var plotCss = {
                top: '5px',
                margin: 'auto',
                position: 'relative',
                height: height * 0.9 + 'px',
                width: dimension + 'px',
            };
            plotCanvas.css(plotCss);
            var thresholds = [];
            for (var i = 0; i < data.thresholds.length; i++) {
                thresholds.push({
                    value: data.thresholds[i],
                    color: data.colorMap[i],
                });
            }
            thresholds.push({
                value: panel.gauge.maxValue,
                color: data.colorMap[data.colorMap.length - 1],
            });
            var bgColor = app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].bootData.user.lightTheme ? 'rgb(230,230,230)' : 'rgb(38,38,38)';
            var fontScale = parseInt(panel.valueFontSize, 10) / 100;
            var fontSize = Math.min(dimension / 5, 100) * fontScale;
            // Reduce gauge width if threshold labels enabled
            var gaugeWidthReduceRatio = panel.gauge.thresholdLabels ? 1.5 : 1;
            var gaugeWidth = Math.min(dimension / 6, 60) / gaugeWidthReduceRatio;
            var thresholdMarkersWidth = gaugeWidth / 5;
            var thresholdLabelFontSize = fontSize / 2.5;
            var options = {
                series: {
                    gauges: {
                        gauge: {
                            min: panel.gauge.minValue,
                            max: panel.gauge.maxValue,
                            background: { color: bgColor },
                            border: { color: null },
                            shadow: { show: false },
                            width: gaugeWidth,
                        },
                        frame: { show: false },
                        label: { show: false },
                        layout: { margin: 0, thresholdWidth: 0 },
                        cell: { border: { width: 0 } },
                        threshold: {
                            values: thresholds,
                            label: {
                                show: panel.gauge.thresholdLabels,
                                margin: thresholdMarkersWidth + 1,
                                font: { size: thresholdLabelFontSize },
                            },
                            show: panel.gauge.thresholdMarkers,
                            width: thresholdMarkersWidth,
                        },
                        value: {
                            color: panel.colorValue ? getColorForValue(data, data.display.numeric) : null,
                            formatter: function () {
                                return getValueText();
                            },
                            font: {
                                size: fontSize,
                                family: app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].theme.typography.fontFamily.sansSerif,
                            },
                        },
                        show: true,
                    },
                },
            };
            elem.append(plotCanvas);
            var plotSeries = {
                data: [[0, data.value]],
            };
            jquery__WEBPACK_IMPORTED_MODULE_2___default.a.plot(plotCanvas, [plotSeries], options);
        }
        function addSparkline() {
            var data = ctrl.data;
            var width = elem.width();
            if (width < 30) {
                // element has not gotten it's width yet
                // delay sparkline render
                setTimeout(addSparkline, 30);
                return;
            }
            if (!data.sparkline || !data.sparkline.length) {
                // no sparkline data
                return;
            }
            var height = ctrl.height;
            var plotCanvas = jquery__WEBPACK_IMPORTED_MODULE_2___default()('<div></div>');
            var plotCss = {};
            plotCss.position = 'absolute';
            plotCss.bottom = '0px';
            if (panel.sparkline.full) {
                plotCss.left = '0px';
                plotCss.width = width + 'px';
                var dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5;
                plotCss.height = height - dynamicHeightMargin + 'px';
            }
            else {
                plotCss.left = '0px';
                plotCss.width = width + 'px';
                plotCss.height = Math.floor(height * 0.25) + 'px';
            }
            plotCanvas.css(plotCss);
            var options = {
                legend: { show: false },
                series: {
                    lines: {
                        show: true,
                        fill: 1,
                        lineWidth: 1,
                        fillColor: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["getColorFromHexRgbOrName"])(panel.sparkline.fillColor, app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].theme.type),
                        zero: false,
                    },
                },
                yaxis: {
                    show: false,
                    min: panel.sparkline.ymin,
                    max: panel.sparkline.ymax,
                },
                xaxis: {
                    show: false,
                    mode: 'time',
                    min: ctrl.range.from.valueOf(),
                    max: ctrl.range.to.valueOf(),
                },
                grid: { hoverable: false, show: false },
            };
            elem.append(plotCanvas);
            var plotSeries = {
                data: data.sparkline,
                color: Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["getColorFromHexRgbOrName"])(panel.sparkline.lineColor, app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].theme.type),
            };
            jquery__WEBPACK_IMPORTED_MODULE_2___default.a.plot(plotCanvas, [plotSeries], options);
        }
        function render() {
            if (!ctrl.data) {
                return;
            }
            var data = ctrl.data, panel = ctrl.panel;
            // get thresholds
            data.thresholds = panel.thresholds
                ? panel.thresholds.split(',').map(function (strVale) {
                    return Number(strVale.trim());
                })
                : [];
            // Map panel colors to hex or rgb/a values
            if (panel.colors) {
                data.colorMap = panel.colors.map(function (color) { return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_6__["getColorFromHexRgbOrName"])(color, app_core_config__WEBPACK_IMPORTED_MODULE_8__["default"].theme.type); });
            }
            var body = panel.gauge.show ? '' : getBigValueHtml();
            if (panel.colorBackground) {
                var color = getColorForValue(data, data.display.numeric);
                if (color) {
                    $panelContainer.css('background-color', color);
                    if (scope.fullscreen) {
                        elem.css('background-color', color);
                    }
                    else {
                        elem.css('background-color', '');
                    }
                }
                else {
                    $panelContainer.css('background-color', '');
                    elem.css('background-color', '');
                }
            }
            else {
                $panelContainer.css('background-color', '');
                elem.css('background-color', '');
            }
            elem.html(body);
            if (panel.sparkline.show) {
                addSparkline();
            }
            if (panel.gauge.show) {
                addGauge();
            }
            elem.toggleClass('pointer', panel.links.length > 0);
            if (panel.links.length > 0) {
                linkInfo = linkSrv.getDataLinkUIModel(panel.links[0], data.scopedVars, {});
            }
            else {
                linkInfo = null;
            }
        }
        function hookupDrilldownLinkTooltip() {
            // drilldown link tooltip
            var drilldownTooltip = jquery__WEBPACK_IMPORTED_MODULE_2___default()('<div id="tooltip" class="">hello</div>"');
            elem.mouseleave(function () {
                if (panel.links.length === 0) {
                    return;
                }
                $timeout(function () {
                    drilldownTooltip.detach();
                });
            });
            elem.click(function (evt) {
                if (!linkInfo) {
                    return;
                }
                // ignore title clicks in title
                if (jquery__WEBPACK_IMPORTED_MODULE_2___default()(evt).parents('.panel-header').length > 0) {
                    return;
                }
                if (linkInfo.target === '_blank') {
                    window.open(linkInfo.href, '_blank');
                    return;
                }
                if (linkInfo.href.indexOf('http') === 0) {
                    window.location.href = linkInfo.href;
                }
                else {
                    $timeout(function () {
                        $location.url(linkInfo.href);
                    });
                }
                drilldownTooltip.detach();
            });
            elem.mousemove(function (e) {
                if (!linkInfo) {
                    return;
                }
                drilldownTooltip.text('click to go to: ' + linkInfo.title);
                drilldownTooltip.place_tt(e.pageX, e.pageY - 50);
            });
        }
        hookupDrilldownLinkTooltip();
        this.events.on('render', function () {
            render();
            ctrl.renderingCompleted();
        });
    };
    SingleStatCtrl.templateUrl = 'module.html';
    return SingleStatCtrl;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_9__["MetricsPanelCtrl"]));
function getColorForValue(data, value) {
    if (!lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isFinite(value)) {
        return null;
    }
    for (var i = data.thresholds.length; i > 0; i--) {
        if (value >= data.thresholds[i - 1]) {
            return data.colorMap[i];
        }
    }
    return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.first(data.colorMap);
}
function getDistinctNames(data) {
    var e_1, _a, e_2, _b;
    var distinct = {
        byName: {},
        names: [],
    };
    try {
        for (var data_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
            var frame = data_1_1.value;
            var info = { frame: frame };
            try {
                for (var _c = (e_2 = void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](frame.fields)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var field = _d.value;
                    if (field.type === _grafana_data__WEBPACK_IMPORTED_MODULE_10__["FieldType"].time) {
                        if (!info.firstTimeField) {
                            info.firstTimeField = field;
                        }
                    }
                    else {
                        var f = { field: field, frame: info };
                        if (!distinct.first) {
                            distinct.first = f;
                        }
                        var t = field.config.title;
                        if (t && !distinct.byName[t]) {
                            distinct.byName[t] = f;
                            distinct.names.push(t);
                        }
                        t = field.name;
                        if (t && !distinct.byName[t]) {
                            distinct.byName[t] = f;
                            distinct.names.push(t);
                        }
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return distinct;
}



/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/ColoringEditor.tsx":
/*!*****************************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/ColoringEditor.tsx ***!
  \*****************************************************************/
/*! exports provided: ColoringEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColoringEditor", function() { return ColoringEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Components

var labelWidth = 6;
var ColoringEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColoringEditor, _super);
    function ColoringEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onToggleColorBackground = function () {
            return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { colorBackground: !_this.props.options.colorBackground }));
        };
        _this.onToggleColorValue = function () { return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { colorValue: !_this.props.options.colorValue })); };
        _this.onToggleColorPrefix = function () {
            return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { colorPrefix: !_this.props.options.colorPrefix }));
        };
        _this.onToggleColorPostfix = function () {
            return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { colorPostfix: !_this.props.options.colorPostfix }));
        };
        return _this;
    }
    ColoringEditor.prototype.render = function () {
        var _a = this.props.options, colorBackground = _a.colorBackground, colorValue = _a.colorValue, colorPrefix = _a.colorPrefix, colorPostfix = _a.colorPostfix;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Coloring" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Background", labelClass: "width-" + labelWidth, checked: colorBackground, onChange: this.onToggleColorBackground }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Value", labelClass: "width-" + labelWidth, checked: colorValue, onChange: this.onToggleColorValue }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Prefix", labelClass: "width-" + labelWidth, checked: colorPrefix, onChange: this.onToggleColorPrefix }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Postfix", labelClass: "width-" + labelWidth, checked: colorPostfix, onChange: this.onToggleColorPostfix })));
    };
    return ColoringEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/FontSizeEditor.tsx":
/*!*****************************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/FontSizeEditor.tsx ***!
  \*****************************************************************/
/*! exports provided: FontSizeEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FontSizeEditor", function() { return FontSizeEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Components

var labelWidth = 6;
var percents = ['20%', '30%', '50%', '70%', '80%', '100%', '110%', '120%', '150%', '170%', '200%'];
var fontSizeOptions = percents.map(function (v) {
    return { value: v, label: v };
});
var FontSizeEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FontSizeEditor, _super);
    function FontSizeEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.setPrefixFontSize = function (v) {
            return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { prefixFontSize: v.value }));
        };
        _this.setValueFontSize = function (v) {
            return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { valueFontSize: v.value }));
        };
        _this.setPostfixFontSize = function (v) {
            return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { postfixFontSize: v.value }));
        };
        return _this;
    }
    FontSizeEditor.prototype.render = function () {
        var _a = this.props.options, prefixFontSize = _a.prefixFontSize, valueFontSize = _a.valueFontSize, postfixFontSize = _a.postfixFontSize;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Font Size" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Prefix"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { width: 12, options: fontSizeOptions, onChange: this.setPrefixFontSize, value: fontSizeOptions.find(function (option) { return option.value === prefixFontSize; }) })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Value"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { width: 12, options: fontSizeOptions, onChange: this.setValueFontSize, value: fontSizeOptions.find(function (option) { return option.value === valueFontSize; }) })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormLabel"], { width: labelWidth }, "Postfix"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { width: 12, options: fontSizeOptions, onChange: this.setPostfixFontSize, value: fontSizeOptions.find(function (option) { return option.value === postfixFontSize; }) }))));
    };
    return FontSizeEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/SingleStatEditor.tsx":
/*!*******************************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/SingleStatEditor.tsx ***!
  \*******************************************************************/
/*! exports provided: SingleStatEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SingleStatEditor", function() { return SingleStatEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _ColoringEditor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ColoringEditor */ "./public/app/plugins/panel/singlestat2/ColoringEditor.tsx");
/* harmony import */ var _FontSizeEditor__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./FontSizeEditor */ "./public/app/plugins/panel/singlestat2/FontSizeEditor.tsx");
/* harmony import */ var _SparklineEditor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SparklineEditor */ "./public/app/plugins/panel/singlestat2/SparklineEditor.tsx");
/* harmony import */ var app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/features/panel/panellinks/link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");

// Libraries






var SingleStatEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SingleStatEditor, _super);
    function SingleStatEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onThresholdsChanged = function (thresholds) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { thresholds: thresholds }));
        };
        _this.onValueMappingsChanged = function (mappings) {
            var current = _this.props.options.fieldOptions.defaults;
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, current, { mappings: mappings }));
        };
        _this.onDisplayOptionsChanged = function (fieldOptions) {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { fieldOptions: fieldOptions }));
        };
        _this.onSparklineChanged = function (sparkline) {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { sparkline: sparkline }));
        };
        _this.onDefaultsChange = function (field) {
            _this.onDisplayOptionsChanged(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions, { defaults: field }));
        };
        _this.onDataLinksChanged = function (links) {
            _this.onDefaultsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options.fieldOptions.defaults, { links: links }));
        };
        return _this;
    }
    SingleStatEditor.prototype.render = function () {
        var options = this.props.options;
        var fieldOptions = options.fieldOptions;
        var defaults = fieldOptions.defaults;
        var suggestions = fieldOptions.values
            ? Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_6__["getDataLinksVariableSuggestions"])(this.props.data.series)
            : Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_6__["getCalculationValueDataLinksVariableSuggestions"])(this.props.data.series);
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGrid"], null,
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Display" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldDisplayEditor"], { onChange: this.onDisplayOptionsChanged, value: fieldOptions })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Field (default)" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FieldPropertiesEditor"], { showMinMax: true, onChange: this.onDefaultsChange, value: defaults })),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_FontSizeEditor__WEBPACK_IMPORTED_MODULE_4__["FontSizeEditor"], { options: options, onChange: this.props.onOptionsChange }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_ColoringEditor__WEBPACK_IMPORTED_MODULE_3__["ColoringEditor"], { options: options, onChange: this.props.onOptionsChange }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_SparklineEditor__WEBPACK_IMPORTED_MODULE_5__["SparklineEditor"], { options: options.sparkline, onChange: this.onSparklineChanged }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ThresholdsEditor"], { onChange: this.onThresholdsChanged, thresholds: defaults.thresholds })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ValueMappingsEditor"], { onChange: this.onValueMappingsChanged, valueMappings: defaults.mappings }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Data links" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["DataLinksEditor"], { value: defaults.links, onChange: this.onDataLinksChanged, suggestions: suggestions, maxLinks: 10 }))));
    };
    return SingleStatEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/SingleStatPanel.tsx":
/*!******************************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/SingleStatPanel.tsx ***!
  \******************************************************************/
/*! exports provided: SingleStatPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SingleStatPanel", function() { return SingleStatPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/panel/panellinks/linkSuppliers */ "./public/app/features/panel/panellinks/linkSuppliers.ts");

// Libraries

// Utils & Services



var SingleStatPanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SingleStatPanel, _super);
    function SingleStatPanel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.renderValue = function (value, width, height) {
            var sparkline;
            if (value.sparkline) {
                var _a = _this.props, timeRange = _a.timeRange, options = _a.options;
                sparkline = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options.sparkline, { data: value.sparkline, minX: timeRange.from.valueOf(), maxX: timeRange.to.valueOf() });
            }
            return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["DataLinksContextMenu"], { links: Object(app_features_panel_panellinks_linkSuppliers__WEBPACK_IMPORTED_MODULE_4__["getFieldLinksSupplier"])(value) }, function (_a) {
                var openMenu = _a.openMenu, targetClassName = _a.targetClassName;
                return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["BigValue"], { value: value.display, sparkline: sparkline, width: width, height: height, theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme, onClick: openMenu, className: targetClassName }));
            }));
        };
        _this.getValues = function () {
            var _a = _this.props, data = _a.data, options = _a.options, replaceVariables = _a.replaceVariables;
            return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["getFieldDisplayValues"])(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, options, { replaceVariables: replaceVariables, theme: app_core_config__WEBPACK_IMPORTED_MODULE_2__["config"].theme, data: data.series, sparkline: options.sparkline.show }));
        };
        return _this;
    }
    SingleStatPanel.prototype.render = function () {
        var _a = this.props, height = _a.height, width = _a.width, options = _a.options, data = _a.data, renderCounter = _a.renderCounter;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_3__["VizRepeater"], { getValues: this.getValues, renderValue: this.renderValue, width: width, height: height, source: data, renderCounter: renderCounter, orientation: options.orientation }));
    };
    return SingleStatPanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/SparklineEditor.tsx":
/*!******************************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/SparklineEditor.tsx ***!
  \******************************************************************/
/*! exports provided: SparklineEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SparklineEditor", function() { return SparklineEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Components

var labelWidth = 6;
var SparklineEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SparklineEditor, _super);
    function SparklineEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onToggleShow = function () { return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { show: !_this.props.options.show })); };
        _this.onToggleFull = function () { return _this.props.onChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { full: !_this.props.options.full })); };
        return _this;
    }
    SparklineEditor.prototype.render = function () {
        var _a = this.props.options, show = _a.show, full = _a.full;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Sparkline" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Show", labelClass: "width-" + labelWidth, checked: show, onChange: this.onToggleShow }),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Full Height", labelClass: "width-" + labelWidth, checked: full, onChange: this.onToggleFull })));
    };
    return SparklineEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/module.tsx":
/*!*********************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/module.tsx ***!
  \*********************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/singlestat2/types.ts");
/* harmony import */ var _SingleStatPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SingleStatPanel */ "./public/app/plugins/panel/singlestat2/SingleStatPanel.tsx");
/* harmony import */ var _SingleStatEditor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./SingleStatEditor */ "./public/app/plugins/panel/singlestat2/SingleStatEditor.tsx");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_SingleStatPanel__WEBPACK_IMPORTED_MODULE_2__["SingleStatPanel"])
    .setDefaults(_types__WEBPACK_IMPORTED_MODULE_1__["defaults"])
    .setEditor(_SingleStatEditor__WEBPACK_IMPORTED_MODULE_3__["SingleStatEditor"])
    .setPanelChangeHandler(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatPanelChangedHandler"])
    .setMigrationHandler(_grafana_ui__WEBPACK_IMPORTED_MODULE_0__["sharedSingleStatMigrationHandler"]);


/***/ }),

/***/ "./public/app/plugins/panel/singlestat2/types.ts":
/*!*******************************************************!*\
  !*** ./public/app/plugins/panel/singlestat2/types.ts ***!
  \*******************************************************/
/*! exports provided: standardFieldDisplayOptions, defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "standardFieldDisplayOptions", function() { return standardFieldDisplayOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");


var standardFieldDisplayOptions = {
    values: false,
    calcs: [_grafana_data__WEBPACK_IMPORTED_MODULE_1__["ReducerID"].mean],
    defaults: {
        min: 0,
        max: 100,
        thresholds: [
            { value: -Infinity, color: 'green' },
            { value: 80, color: 'red' },
        ],
        mappings: [],
    },
    override: {},
};
var defaults = {
    sparkline: {
        show: true,
        full: false,
        lineColor: 'rgb(31, 120, 193)',
        fillColor: 'rgba(31, 118, 189, 0.18)',
    },
    fieldOptions: standardFieldDisplayOptions,
    orientation: _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["VizOrientation"].Auto,
    colorBackground: false,
    colorValue: false,
    colorPrefix: false,
    colorPostfix: false,
};


/***/ }),

/***/ "./public/app/plugins/panel/table/column_options.ts":
/*!**********************************************************!*\
  !*** ./public/app/plugins/panel/table/column_options.ts ***!
  \**********************************************************/
/*! exports provided: ColumnOptionsCtrl, columnOptionsTab */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColumnOptionsCtrl", function() { return ColumnOptionsCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "columnOptionsTab", function() { return columnOptionsTab; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


var ColumnOptionsCtrl = /** @class */ (function () {
    /** @ngInject */
    function ColumnOptionsCtrl($scope) {
        var _this = this;
        $scope.editor = this;
        this.activeStyleIndex = 0;
        this.panelCtrl = $scope.ctrl;
        this.panel = this.panelCtrl.panel;
        this.unitFormats = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getValueFormats"])();
        this.colorModes = [
            { text: 'Disabled', value: null },
            { text: 'Cell', value: 'cell' },
            { text: 'Value', value: 'value' },
            { text: 'Row', value: 'row' },
        ];
        this.columnTypes = [
            { text: 'Number', value: 'number' },
            { text: 'String', value: 'string' },
            { text: 'Date', value: 'date' },
            { text: 'Hidden', value: 'hidden' },
        ];
        this.fontSizes = ['80%', '90%', '100%', '110%', '120%', '130%', '150%', '160%', '180%', '200%', '220%', '250%'];
        this.dateFormats = [
            { text: 'YYYY-MM-DD HH:mm:ss', value: 'YYYY-MM-DD HH:mm:ss' },
            { text: 'YYYY-MM-DD HH:mm:ss.SSS', value: 'YYYY-MM-DD HH:mm:ss.SSS' },
            { text: 'MM/DD/YY h:mm:ss a', value: 'MM/DD/YY h:mm:ss a' },
            { text: 'MMMM D, YYYY LT', value: 'MMMM D, YYYY LT' },
            { text: 'YYYY-MM-DD', value: 'YYYY-MM-DD' },
        ];
        this.mappingTypes = [{ text: 'Value to text', value: 1 }, { text: 'Range to text', value: 2 }];
        this.getColumnNames = function () {
            if (!_this.panelCtrl.table) {
                return [];
            }
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(_this.panelCtrl.table.columns, function (col) {
                return col.text;
            });
        };
        this.onColorChange = this.onColorChange.bind(this);
    }
    ColumnOptionsCtrl.prototype.render = function () {
        this.panelCtrl.render();
    };
    ColumnOptionsCtrl.prototype.setUnitFormat = function (column, subItem) {
        column.unit = subItem.value;
        this.panelCtrl.render();
    };
    ColumnOptionsCtrl.prototype.addColumnStyle = function () {
        var newStyleRule = {
            unit: 'short',
            type: 'number',
            alias: '',
            decimals: 2,
            colors: ['rgba(245, 54, 54, 0.9)', 'rgba(237, 129, 40, 0.89)', 'rgba(50, 172, 45, 0.97)'],
            colorMode: null,
            pattern: '',
            dateFormat: 'YYYY-MM-DD HH:mm:ss',
            thresholds: [],
            mappingType: 1,
        };
        var styles = this.panel.styles;
        var stylesCount = styles.length;
        var indexToInsert = stylesCount;
        // check if last is a catch all rule, then add it before that one
        if (stylesCount > 0) {
            var last = styles[stylesCount - 1];
            if (last.pattern === '/.*/') {
                indexToInsert = stylesCount - 1;
            }
        }
        styles.splice(indexToInsert, 0, newStyleRule);
        this.activeStyleIndex = indexToInsert;
    };
    ColumnOptionsCtrl.prototype.removeColumnStyle = function (style) {
        this.panel.styles = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.without(this.panel.styles, style);
    };
    ColumnOptionsCtrl.prototype.invertColorOrder = function (index) {
        var ref = this.panel.styles[index].colors;
        var copy = ref[0];
        ref[0] = ref[2];
        ref[2] = copy;
        this.panelCtrl.render();
    };
    ColumnOptionsCtrl.prototype.onColorChange = function (style, colorIndex) {
        var _this = this;
        return function (newColor) {
            style.colors[colorIndex] = newColor;
            _this.render();
        };
    };
    ColumnOptionsCtrl.prototype.addValueMap = function (style) {
        if (!style.valueMaps) {
            style.valueMaps = [];
        }
        style.valueMaps.push({ value: '', text: '' });
        this.panelCtrl.render();
    };
    ColumnOptionsCtrl.prototype.removeValueMap = function (style, index) {
        style.valueMaps.splice(index, 1);
        this.panelCtrl.render();
    };
    ColumnOptionsCtrl.prototype.addRangeMap = function (style) {
        if (!style.rangeMaps) {
            style.rangeMaps = [];
        }
        style.rangeMaps.push({ from: '', to: '', text: '' });
        this.panelCtrl.render();
    };
    ColumnOptionsCtrl.prototype.removeRangeMap = function (style, index) {
        style.rangeMaps.splice(index, 1);
        this.panelCtrl.render();
    };
    return ColumnOptionsCtrl;
}());

/** @ngInject */
function columnOptionsTab($q, uiSegmentSrv) {
    'use strict';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'public/app/plugins/panel/table/column_options.html',
        controller: ColumnOptionsCtrl,
    };
}


/***/ }),

/***/ "./public/app/plugins/panel/table/editor.ts":
/*!**************************************************!*\
  !*** ./public/app/plugins/panel/table/editor.ts ***!
  \**************************************************/
/*! exports provided: TablePanelEditorCtrl, tablePanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TablePanelEditorCtrl", function() { return TablePanelEditorCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tablePanelEditor", function() { return tablePanelEditor; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _transformers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./transformers */ "./public/app/plugins/panel/table/transformers.ts");


var TablePanelEditorCtrl = /** @class */ (function () {
    /** @ngInject */
    function TablePanelEditorCtrl($scope, $q, uiSegmentSrv) {
        this.$q = $q;
        this.uiSegmentSrv = uiSegmentSrv;
        $scope.editor = this;
        this.panelCtrl = $scope.ctrl;
        this.panel = this.panelCtrl.panel;
        this.transformers = _transformers__WEBPACK_IMPORTED_MODULE_1__["transformers"];
        this.fontSizes = ['80%', '90%', '100%', '110%', '120%', '130%', '150%', '160%', '180%', '200%', '220%', '250%'];
        this.addColumnSegment = uiSegmentSrv.newPlusButton();
        this.updateTransformHints();
    }
    TablePanelEditorCtrl.prototype.updateTransformHints = function () {
        this.canSetColumns = false;
        this.columnsHelpMessage = '';
        switch (this.panel.transform) {
            case 'timeseries_aggregations': {
                this.canSetColumns = true;
                break;
            }
            case 'json': {
                this.canSetColumns = true;
                break;
            }
            case 'table': {
                this.columnsHelpMessage = 'Columns and their order are determined by the data query';
            }
        }
    };
    TablePanelEditorCtrl.prototype.getColumnOptions = function () {
        var _this = this;
        if (!this.panelCtrl.dataRaw) {
            return this.$q.when([]);
        }
        var columns = this.transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw);
        var segments = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.map(columns, function (c) { return _this.uiSegmentSrv.newSegment({ value: c.text }); });
        return this.$q.when(segments);
    };
    TablePanelEditorCtrl.prototype.addColumn = function () {
        var columns = _transformers__WEBPACK_IMPORTED_MODULE_1__["transformers"][this.panel.transform].getColumns(this.panelCtrl.dataRaw);
        var column = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.find(columns, { text: this.addColumnSegment.value });
        if (column) {
            this.panel.columns.push(column);
            this.render();
        }
        var plusButton = this.uiSegmentSrv.newPlusButton();
        this.addColumnSegment.html = plusButton.html;
        this.addColumnSegment.value = plusButton.value;
    };
    TablePanelEditorCtrl.prototype.transformChanged = function () {
        this.panel.columns = [];
        if (this.panel.transform === 'timeseries_aggregations') {
            this.panel.columns.push({ text: 'Avg', value: 'avg' });
        }
        this.updateTransformHints();
        this.render();
    };
    TablePanelEditorCtrl.prototype.render = function () {
        this.panelCtrl.render();
    };
    TablePanelEditorCtrl.prototype.removeColumn = function (column) {
        this.panel.columns = lodash__WEBPACK_IMPORTED_MODULE_0___default.a.without(this.panel.columns, column);
        this.panelCtrl.render();
    };
    return TablePanelEditorCtrl;
}());

/** @ngInject */
function tablePanelEditor($q, uiSegmentSrv) {
    'use strict';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'public/app/plugins/panel/table/editor.html',
        controller: TablePanelEditorCtrl,
    };
}


/***/ }),

/***/ "./public/app/plugins/panel/table/module.ts":
/*!**************************************************!*\
  !*** ./public/app/plugins/panel/table/module.ts ***!
  \**************************************************/
/*! exports provided: TablePanelCtrl, PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TablePanelCtrl", function() { return TablePanelCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return TablePanelCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _transformers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./transformers */ "./public/app/plugins/panel/table/transformers.ts");
/* harmony import */ var _editor__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./editor */ "./public/app/plugins/panel/table/editor.ts");
/* harmony import */ var _column_options__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./column_options */ "./public/app/plugins/panel/table/column_options.ts");
/* harmony import */ var _renderer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./renderer */ "./public/app/plugins/panel/table/renderer.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");










var TablePanelCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TablePanelCtrl, _super);
    /** @ngInject */
    function TablePanelCtrl($scope, $injector, templateSrv, annotationsSrv, $sanitize, variableSrv) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.annotationsSrv = annotationsSrv;
        _this.$sanitize = $sanitize;
        _this.variableSrv = variableSrv;
        _this.panelDefaults = {
            targets: [{}],
            transform: 'timeseries_to_columns',
            pageSize: null,
            showHeader: true,
            styles: [
                {
                    type: 'date',
                    pattern: 'Time',
                    alias: 'Time',
                    dateFormat: 'YYYY-MM-DD HH:mm:ss',
                },
                {
                    unit: 'short',
                    type: 'number',
                    alias: '',
                    decimals: 2,
                    colors: ['rgba(245, 54, 54, 0.9)', 'rgba(237, 129, 40, 0.89)', 'rgba(50, 172, 45, 0.97)'],
                    colorMode: null,
                    pattern: '/.*/',
                    thresholds: [],
                },
            ],
            columns: [],
            fontSize: '100%',
            sort: { col: 0, desc: true },
        };
        _this.pageIndex = 0;
        if (_this.panel.styles === void 0) {
            _this.panel.styles = _this.panel.columns;
            _this.panel.columns = _this.panel.fields;
            delete _this.panel.columns;
            delete _this.panel.fields;
        }
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.panel, _this.panelDefaults);
        _this.events.on('data-received', _this.onDataReceived.bind(_this));
        _this.events.on('data-error', _this.onDataError.bind(_this));
        _this.events.on('data-snapshot-load', _this.onDataReceived.bind(_this));
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.events.on('init-panel-actions', _this.onInitPanelActions.bind(_this));
        return _this;
    }
    TablePanelCtrl.prototype.onInitEditMode = function () {
        this.addEditorTab('Options', _editor__WEBPACK_IMPORTED_MODULE_6__["tablePanelEditor"], 2);
        this.addEditorTab('Column Styles', _column_options__WEBPACK_IMPORTED_MODULE_7__["columnOptionsTab"], 3);
    };
    TablePanelCtrl.prototype.onInitPanelActions = function (actions) {
        actions.push({ text: 'Export CSV', click: 'ctrl.exportCsv()' });
    };
    TablePanelCtrl.prototype.issueQueries = function (datasource) {
        var _this = this;
        this.pageIndex = 0;
        if (this.panel.transform === 'annotations') {
            return this.annotationsSrv
                .getAnnotations({
                dashboard: this.dashboard,
                panel: this.panel,
                range: this.range,
            })
                .then(function (anno) {
                _this.loading = false;
                _this.dataRaw = anno;
                _this.pageIndex = 0;
                _this.render();
                return { data: _this.dataRaw }; // Not used
            });
        }
        return _super.prototype.issueQueries.call(this, datasource);
    };
    TablePanelCtrl.prototype.onDataError = function (err) {
        this.dataRaw = [];
        this.render();
    };
    TablePanelCtrl.prototype.onDataReceived = function (dataList) {
        this.dataRaw = dataList;
        this.pageIndex = 0;
        // automatically correct transform mode based on data
        if (this.dataRaw && this.dataRaw.length) {
            if (Object(_grafana_data__WEBPACK_IMPORTED_MODULE_9__["isTableData"])(this.dataRaw[0])) {
                this.panel.transform = 'table';
            }
            else {
                if (this.dataRaw[0].type === 'docs') {
                    this.panel.transform = 'json';
                }
                else {
                    if (this.panel.transform === 'table' || this.panel.transform === 'json') {
                        this.panel.transform = 'timeseries_to_rows';
                    }
                }
            }
        }
        this.render();
    };
    TablePanelCtrl.prototype.render = function () {
        this.table = Object(_transformers__WEBPACK_IMPORTED_MODULE_5__["transformDataToTable"])(this.dataRaw, this.panel);
        this.table.sort(this.panel.sort);
        this.renderer = new _renderer__WEBPACK_IMPORTED_MODULE_8__["TableRenderer"](this.panel, this.table, this.dashboard.isTimezoneUtc(), this.$sanitize, this.templateSrv, app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].theme.type);
        return _super.prototype.render.call(this, this.table);
    };
    TablePanelCtrl.prototype.toggleColumnSort = function (col, colIndex) {
        // remove sort flag from current column
        if (this.table.columns[this.panel.sort.col]) {
            this.table.columns[this.panel.sort.col].sort = false;
        }
        if (this.panel.sort.col === colIndex) {
            if (this.panel.sort.desc) {
                this.panel.sort.desc = false;
            }
            else {
                this.panel.sort.col = null;
            }
        }
        else {
            this.panel.sort.col = colIndex;
            this.panel.sort.desc = true;
        }
        this.render();
    };
    TablePanelCtrl.prototype.exportCsv = function () {
        var scope = this.$scope.$new(true);
        scope.tableData = this.renderer.render_values();
        scope.panel = 'table';
        this.publishAppEvent('show-modal', {
            templateHtml: '<export-data-modal panel="panel" data="tableData"></export-data-modal>',
            scope: scope,
            modalClass: 'modal--narrow',
        });
    };
    TablePanelCtrl.prototype.link = function (scope, elem, attrs, ctrl) {
        var data;
        var panel = ctrl.panel;
        var pageCount = 0;
        function getTableHeight() {
            var panelHeight = ctrl.height;
            if (pageCount > 1) {
                panelHeight -= 26;
            }
            return panelHeight - 31 + 'px';
        }
        function appendTableRows(tbodyElem) {
            ctrl.renderer.setTable(data);
            tbodyElem.empty();
            tbodyElem.html(ctrl.renderer.render(ctrl.pageIndex));
        }
        function switchPage(e) {
            var el = jquery__WEBPACK_IMPORTED_MODULE_2___default()(e.currentTarget);
            ctrl.pageIndex = parseInt(el.text(), 10) - 1;
            renderPanel();
        }
        function appendPaginationControls(footerElem) {
            footerElem.empty();
            var pageSize = panel.pageSize || 100;
            pageCount = Math.ceil(data.rows.length / pageSize);
            if (pageCount === 1) {
                return;
            }
            var startPage = Math.max(ctrl.pageIndex - 3, 0);
            var endPage = Math.min(pageCount, startPage + 9);
            var paginationList = jquery__WEBPACK_IMPORTED_MODULE_2___default()('<ul></ul>');
            for (var i = startPage; i < endPage; i++) {
                var activeClass = i === ctrl.pageIndex ? 'active' : '';
                var pageLinkElem = jquery__WEBPACK_IMPORTED_MODULE_2___default()('<li><a class="table-panel-page-link pointer ' + activeClass + '">' + (i + 1) + '</a></li>');
                paginationList.append(pageLinkElem);
            }
            footerElem.append(paginationList);
        }
        function renderPanel() {
            var panelElem = elem.parents('.panel-content');
            var rootElem = elem.find('.table-panel-scroll');
            var tbodyElem = elem.find('tbody');
            var footerElem = elem.find('.table-panel-footer');
            elem.css({ 'font-size': panel.fontSize });
            panelElem.addClass('table-panel-content');
            appendTableRows(tbodyElem);
            appendPaginationControls(footerElem);
            rootElem.css({ 'max-height': getTableHeight() });
        }
        // hook up link tooltips
        elem.tooltip({
            selector: '[data-link-tooltip]',
        });
        function addFilterClicked(e) {
            var filterData = jquery__WEBPACK_IMPORTED_MODULE_2___default()(e.currentTarget).data();
            var options = {
                datasource: panel.datasource,
                key: data.columns[filterData.column].text,
                value: data.rows[filterData.row][filterData.column],
                operator: filterData.operator,
            };
            ctrl.variableSrv.setAdhocFilter(options);
        }
        elem.on('click', '.table-panel-page-link', switchPage);
        elem.on('click', '.table-panel-filter-link', addFilterClicked);
        var unbindDestroy = scope.$on('$destroy', function () {
            elem.off('click', '.table-panel-page-link');
            elem.off('click', '.table-panel-filter-link');
            unbindDestroy();
        });
        ctrl.events.on('render', function (renderData) {
            data = renderData || data;
            if (data) {
                renderPanel();
            }
            ctrl.renderingCompleted();
        });
    };
    TablePanelCtrl.templateUrl = 'module.html';
    return TablePanelCtrl;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_3__["MetricsPanelCtrl"]));



/***/ }),

/***/ "./public/app/plugins/panel/table/renderer.ts":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/table/renderer.ts ***!
  \****************************************************/
/*! exports provided: TableRenderer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TableRenderer", function() { return TableRenderer; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");




var TableRenderer = /** @class */ (function () {
    function TableRenderer(panel, table, isUtc, sanitize, templateSrv, theme) {
        this.panel = panel;
        this.table = table;
        this.isUtc = isUtc;
        this.sanitize = sanitize;
        this.templateSrv = templateSrv;
        this.theme = theme;
        this.initColumns();
    }
    TableRenderer.prototype.setTable = function (table) {
        this.table = table;
        this.initColumns();
    };
    TableRenderer.prototype.initColumns = function () {
        this.formatters = [];
        this.colorState = {};
        for (var colIndex = 0; colIndex < this.table.columns.length; colIndex++) {
            var column = this.table.columns[colIndex];
            column.title = column.text;
            for (var i = 0; i < this.panel.styles.length; i++) {
                var style = this.panel.styles[i];
                var regex = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["stringToJsRegex"])(style.pattern);
                if (column.text.match(regex)) {
                    column.style = style;
                    if (style.alias) {
                        column.title = column.text.replace(regex, style.alias);
                    }
                    break;
                }
            }
            this.formatters[colIndex] = this.createColumnFormatter(column);
        }
    };
    TableRenderer.prototype.getColorForValue = function (value, style) {
        if (!style.thresholds || !style.colors) {
            return null;
        }
        for (var i = style.thresholds.length; i > 0; i--) {
            if (value >= style.thresholds[i - 1]) {
                return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getColorFromHexRgbOrName"])(style.colors[i], this.theme);
            }
        }
        return Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getColorFromHexRgbOrName"])(lodash__WEBPACK_IMPORTED_MODULE_0___default.a.first(style.colors), this.theme);
    };
    TableRenderer.prototype.defaultCellFormatter = function (v, style) {
        if (v === null || v === void 0 || v === undefined) {
            return '';
        }
        if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(v)) {
            v = v.join(', ');
        }
        if (style && style.sanitize) {
            return this.sanitize(v);
        }
        else {
            return lodash__WEBPACK_IMPORTED_MODULE_0___default.a.escape(v);
        }
    };
    TableRenderer.prototype.createColumnFormatter = function (column) {
        var _this = this;
        if (!column.style) {
            return this.defaultCellFormatter;
        }
        if (column.style.type === 'hidden') {
            return function (v) { return undefined; };
        }
        if (column.style.type === 'date') {
            return function (v) {
                if (v === undefined || v === null) {
                    return '-';
                }
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(v)) {
                    v = v[0];
                }
                // if is an epoch (numeric string and len > 12)
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(v) && !isNaN(v) && v.length > 12) {
                    v = parseInt(v, 10);
                }
                var date = Object(_grafana_data__WEBPACK_IMPORTED_MODULE_2__["dateTime"])(v);
                if (_this.isUtc) {
                    date = date.utc();
                }
                return date.format(column.style.dateFormat);
            };
        }
        if (column.style.type === 'string') {
            return function (v) {
                if (lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(v)) {
                    v = v.join(', ');
                }
                var mappingType = column.style.mappingType || 0;
                if (mappingType === 1 && column.style.valueMaps) {
                    for (var i = 0; i < column.style.valueMaps.length; i++) {
                        var map = column.style.valueMaps[i];
                        if (v === null) {
                            if (map.value === 'null') {
                                return map.text;
                            }
                            continue;
                        }
                        // Allow both numeric and string values to be mapped
                        if ((!lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isString(v) && Number(map.value) === Number(v)) || map.value === v) {
                            _this.setColorState(v, column.style);
                            return _this.defaultCellFormatter(map.text, column.style);
                        }
                    }
                }
                if (mappingType === 2 && column.style.rangeMaps) {
                    for (var i = 0; i < column.style.rangeMaps.length; i++) {
                        var map = column.style.rangeMaps[i];
                        if (v === null) {
                            if (map.from === 'null' && map.to === 'null') {
                                return map.text;
                            }
                            continue;
                        }
                        if (Number(map.from) <= Number(v) && Number(map.to) >= Number(v)) {
                            _this.setColorState(v, column.style);
                            return _this.defaultCellFormatter(map.text, column.style);
                        }
                    }
                }
                if (v === null || v === void 0) {
                    return '-';
                }
                _this.setColorState(v, column.style);
                return _this.defaultCellFormatter(v, column.style);
            };
        }
        if (column.style.type === 'number') {
            var valueFormatter_1 = Object(_grafana_ui__WEBPACK_IMPORTED_MODULE_1__["getValueFormat"])(column.unit || column.style.unit);
            return function (v) {
                if (v === null || v === void 0) {
                    return '-';
                }
                if (isNaN(v) || lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(v)) {
                    return _this.defaultCellFormatter(v, column.style);
                }
                _this.setColorState(v, column.style);
                return valueFormatter_1(v, column.style.decimals, null);
            };
        }
        return function (value) {
            return _this.defaultCellFormatter(value, column.style);
        };
    };
    TableRenderer.prototype.setColorState = function (value, style) {
        if (!style.colorMode) {
            return;
        }
        if (value === null || value === void 0 || lodash__WEBPACK_IMPORTED_MODULE_0___default.a.isArray(value)) {
            return;
        }
        var numericValue = Number(value);
        if (isNaN(numericValue)) {
            return;
        }
        this.colorState[style.colorMode] = this.getColorForValue(numericValue, style);
    };
    TableRenderer.prototype.renderRowVariables = function (rowIndex) {
        var scopedVars = {};
        var cellVariable;
        var row = this.table.rows[rowIndex];
        for (var i = 0; i < row.length; i++) {
            cellVariable = "__cell_" + i;
            scopedVars[cellVariable] = { value: row[i], text: row[i] ? row[i].toString() : '' };
        }
        return scopedVars;
    };
    TableRenderer.prototype.formatColumnValue = function (colIndex, value) {
        return this.formatters[colIndex] ? this.formatters[colIndex](value) : value;
    };
    TableRenderer.prototype.renderCell = function (columnIndex, rowIndex, value, addWidthHack) {
        if (addWidthHack === void 0) { addWidthHack = false; }
        value = this.formatColumnValue(columnIndex, value);
        var column = this.table.columns[columnIndex];
        var cellStyle = '';
        var textStyle = '';
        var cellClasses = [];
        var cellClass = '';
        if (this.colorState.cell) {
            cellStyle = ' style="background-color:' + this.colorState.cell + '"';
            cellClasses.push('table-panel-color-cell');
            this.colorState.cell = null;
        }
        else if (this.colorState.value) {
            textStyle = ' style="color:' + this.colorState.value + '"';
            this.colorState.value = null;
        }
        // because of the fixed table headers css only solution
        // there is an issue if header cell is wider the cell
        // this hack adds header content to cell (not visible)
        var columnHtml = '';
        if (addWidthHack) {
            columnHtml = '<div class="table-panel-width-hack">' + this.table.columns[columnIndex].title + '</div>';
        }
        if (value === undefined) {
            cellStyle = ' style="display:none;"';
            column.hidden = true;
        }
        else {
            column.hidden = false;
        }
        if (column.hidden === true) {
            return '';
        }
        if (column.style && column.style.preserveFormat) {
            cellClasses.push('table-panel-cell-pre');
        }
        if (column.style && column.style.link) {
            // Render cell as link
            var scopedVars = this.renderRowVariables(rowIndex);
            scopedVars['__cell'] = { value: value, text: value ? value.toString() : '' };
            var cellLink = this.templateSrv.replace(column.style.linkUrl, scopedVars, encodeURIComponent);
            var cellLinkTooltip = this.templateSrv.replace(column.style.linkTooltip, scopedVars);
            var cellTarget = column.style.linkTargetBlank ? '_blank' : '';
            cellClasses.push('table-panel-cell-link');
            columnHtml += "\n        <a href=\"" + cellLink + "\" target=\"" + cellTarget + "\" data-link-tooltip data-original-title=\"" + cellLinkTooltip + "\" data-placement=\"right\"" + textStyle + ">\n          " + value + "\n        </a>\n      ";
        }
        else {
            columnHtml += value;
        }
        if (column.filterable) {
            cellClasses.push('table-panel-cell-filterable');
            columnHtml += "\n        <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter out value\" data-placement=\"bottom\"\n           data-row=\"" + rowIndex + "\" data-column=\"" + columnIndex + "\" data-operator=\"!=\">\n          <i class=\"fa fa-search-minus\"></i>\n        </a>\n        <a class=\"table-panel-filter-link\" data-link-tooltip data-original-title=\"Filter for value\" data-placement=\"bottom\"\n           data-row=\"" + rowIndex + "\" data-column=\"" + columnIndex + "\" data-operator=\"=\">\n          <i class=\"fa fa-search-plus\"></i>\n        </a>";
        }
        if (cellClasses.length) {
            cellClass = ' class="' + cellClasses.join(' ') + '"';
        }
        columnHtml = '<td' + cellClass + cellStyle + textStyle + '>' + columnHtml + '</td>';
        return columnHtml;
    };
    TableRenderer.prototype.render = function (page) {
        var pageSize = this.panel.pageSize || 100;
        var startPos = page * pageSize;
        var endPos = Math.min(startPos + pageSize, this.table.rows.length);
        var html = '';
        for (var y = startPos; y < endPos; y++) {
            var row = this.table.rows[y];
            var cellHtml = '';
            var rowStyle = '';
            var rowClasses = [];
            var rowClass = '';
            for (var i = 0; i < this.table.columns.length; i++) {
                cellHtml += this.renderCell(i, y, row[i], y === startPos);
            }
            if (this.colorState.row) {
                rowStyle = ' style="background-color:' + this.colorState.row + '"';
                rowClasses.push('table-panel-color-row');
                this.colorState.row = null;
            }
            if (rowClasses.length) {
                rowClass = ' class="' + rowClasses.join(' ') + '"';
            }
            html += '<tr ' + rowClass + rowStyle + '>' + cellHtml + '</tr>';
        }
        return html;
    };
    TableRenderer.prototype.render_values = function () {
        var rows = [];
        for (var y = 0; y < this.table.rows.length; y++) {
            var row = this.table.rows[y];
            var newRow = [];
            for (var i = 0; i < this.table.columns.length; i++) {
                newRow.push(this.formatColumnValue(i, row[i]));
            }
            rows.push(newRow);
        }
        return {
            columns: this.table.columns,
            rows: rows,
        };
    };
    return TableRenderer;
}());



/***/ }),

/***/ "./public/app/plugins/panel/table/transformers.ts":
/*!********************************************************!*\
  !*** ./public/app/plugins/panel/table/transformers.ts ***!
  \********************************************************/
/*! exports provided: transformers, transformDataToTable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformers", function() { return transformers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformDataToTable", function() { return transformDataToTable; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_core_utils_flatten__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/core/utils/flatten */ "./public/app/core/utils/flatten.ts");
/* harmony import */ var app_core_time_series2__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/time_series2 */ "./public/app/core/time_series2.ts");
/* harmony import */ var app_core_table_model__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/table_model */ "./public/app/core/table_model.ts");





var transformers = {};
transformers['timeseries_to_rows'] = {
    description: 'Time series to rows',
    getColumns: function () {
        return [];
    },
    transform: function (data, panel, model) {
        model.columns = [{ text: 'Time', type: 'date' }, { text: 'Metric' }, { text: 'Value' }];
        for (var i = 0; i < data.length; i++) {
            var series = data[i];
            for (var y = 0; y < series.datapoints.length; y++) {
                var dp = series.datapoints[y];
                model.rows.push([dp[1], series.target, dp[0]]);
            }
        }
    },
};
transformers['timeseries_to_columns'] = {
    description: 'Time series to columns',
    getColumns: function () {
        return [];
    },
    transform: function (data, panel, model) {
        model.columns.push({ text: 'Time', type: 'date' });
        // group by time
        var points = {};
        for (var i = 0; i < data.length; i++) {
            var series = data[i];
            model.columns.push({ text: series.target });
            for (var y = 0; y < series.datapoints.length; y++) {
                var dp = series.datapoints[y];
                var timeKey = dp[1].toString();
                if (!points[timeKey]) {
                    points[timeKey] = { time: dp[1] };
                    points[timeKey][i] = dp[0];
                }
                else {
                    points[timeKey][i] = dp[0];
                }
            }
        }
        for (var time in points) {
            var point = points[time];
            var values = [point.time];
            for (var i = 0; i < data.length; i++) {
                var value = point[i];
                values.push(value);
            }
            model.rows.push(values);
        }
    },
};
transformers['timeseries_aggregations'] = {
    description: 'Time series aggregations',
    getColumns: function () {
        return [
            { text: 'Avg', value: 'avg' },
            { text: 'Min', value: 'min' },
            { text: 'Max', value: 'max' },
            { text: 'Total', value: 'total' },
            { text: 'Current', value: 'current' },
            { text: 'Count', value: 'count' },
        ];
    },
    transform: function (data, panel, model) {
        var i, y;
        model.columns.push({ text: 'Metric' });
        for (i = 0; i < panel.columns.length; i++) {
            model.columns.push({ text: panel.columns[i].text });
        }
        for (i = 0; i < data.length; i++) {
            var series = new app_core_time_series2__WEBPACK_IMPORTED_MODULE_3__["default"]({
                datapoints: data[i].datapoints,
                alias: data[i].target,
            });
            series.getFlotPairs('connected');
            var cells = [series.alias];
            for (y = 0; y < panel.columns.length; y++) {
                cells.push(series.stats[panel.columns[y].value]);
            }
            model.rows.push(cells);
        }
    },
};
transformers['annotations'] = {
    description: 'Annotations',
    getColumns: function () {
        return [];
    },
    transform: function (data, panel, model) {
        model.columns.push({ text: 'Time', type: 'date' });
        model.columns.push({ text: 'Title' });
        model.columns.push({ text: 'Text' });
        model.columns.push({ text: 'Tags' });
        if (!data || !data.annotations || data.annotations.length === 0) {
            return;
        }
        for (var i = 0; i < data.annotations.length; i++) {
            var evt = data.annotations[i];
            model.rows.push([evt.time, evt.title, evt.text, evt.tags]);
        }
    },
};
transformers['table'] = {
    description: 'Table',
    getColumns: function (data) {
        if (!data || data.length === 0) {
            return [];
        }
        // Single query returns data columns as is
        if (data.length === 1) {
            return tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"](data[0].columns);
        }
        // Track column indexes: name -> index
        var columnNames = {};
        // Union of all columns
        var columns = data.reduce(function (acc, series) {
            series.columns.forEach(function (col) {
                var text = col.text;
                if (columnNames[text] === undefined) {
                    columnNames[text] = acc.length;
                    acc.push(col);
                }
            });
            return acc;
        }, []);
        return columns;
    },
    transform: function (data, panel, model) {
        if (!data || data.length === 0) {
            return;
        }
        var noTableIndex = lodash__WEBPACK_IMPORTED_MODULE_1___default.a.findIndex(data, function (d) { return 'columns' in d && 'rows' in d; });
        if (noTableIndex < 0) {
            throw {
                message: "Result of query #" + String.fromCharCode(65 + noTableIndex) + " is not in table format, try using another transform.",
            };
        }
        app_core_table_model__WEBPACK_IMPORTED_MODULE_4__["mergeTablesIntoModel"].apply(void 0, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([model], data));
    },
};
transformers['json'] = {
    description: 'JSON Data',
    getColumns: function (data) {
        if (!data || data.length === 0) {
            return [];
        }
        var names = {};
        for (var i = 0; i < data.length; i++) {
            var series = data[i];
            if (series.type !== 'docs') {
                continue;
            }
            // only look at 100 docs
            var maxDocs = Math.min(series.datapoints.length, 100);
            for (var y = 0; y < maxDocs; y++) {
                var doc = series.datapoints[y];
                var flattened = Object(app_core_utils_flatten__WEBPACK_IMPORTED_MODULE_2__["default"])(doc, {});
                for (var propName in flattened) {
                    names[propName] = true;
                }
            }
        }
        return lodash__WEBPACK_IMPORTED_MODULE_1___default.a.map(names, function (value, key) {
            return { text: key, value: key };
        });
    },
    transform: function (data, panel, model) {
        var e_1, _a;
        var i, y, z;
        try {
            for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](panel.columns), _c = _b.next(); !_c.done; _c = _b.next()) {
                var column = _c.value;
                var tableCol = { text: column.text };
                // if filterable data then set columns to filterable
                if (data.length > 0 && data[0].filterable) {
                    tableCol.filterable = true;
                }
                model.columns.push(tableCol);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        if (model.columns.length === 0) {
            model.columns.push({ text: 'JSON' });
        }
        for (i = 0; i < data.length; i++) {
            var series = data[i];
            for (y = 0; y < series.datapoints.length; y++) {
                var dp = series.datapoints[y];
                var values = [];
                if (lodash__WEBPACK_IMPORTED_MODULE_1___default.a.isObject(dp) && panel.columns.length > 0) {
                    var flattened = Object(app_core_utils_flatten__WEBPACK_IMPORTED_MODULE_2__["default"])(dp);
                    for (z = 0; z < panel.columns.length; z++) {
                        values.push(flattened[panel.columns[z].value]);
                    }
                }
                else {
                    values.push(JSON.stringify(dp));
                }
                model.rows.push(values);
            }
        }
    },
};
function transformDataToTable(data, panel) {
    var model = new app_core_table_model__WEBPACK_IMPORTED_MODULE_4__["default"]();
    if (!data || data.length === 0) {
        return model;
    }
    var transformer = transformers[panel.transform];
    if (!transformer) {
        throw { message: 'Transformer ' + panel.transform + ' not found' };
    }
    transformer.transform(data, panel, model);
    return model;
}



/***/ }),

/***/ "./public/app/plugins/panel/table2/TablePanel.tsx":
/*!********************************************************!*\
  !*** ./public/app/plugins/panel/table2/TablePanel.tsx ***!
  \********************************************************/
/*! exports provided: TablePanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TablePanel", function() { return TablePanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_ui_src_components_Table_Table__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/ui/src/components/Table/Table */ "./packages/grafana-ui/src/components/Table/Table.tsx");

// Libraries

// Types


var TablePanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TablePanel, _super);
    function TablePanel(props) {
        return _super.call(this, props) || this;
    }
    TablePanel.prototype.render = function () {
        var _this = this;
        var _a = this.props, data = _a.data, options = _a.options;
        if (data.series.length < 1) {
            return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, "No Table Data...");
        }
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["ThemeContext"].Consumer, null, function (theme) { return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui_src_components_Table_Table__WEBPACK_IMPORTED_MODULE_3__["default"], tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props, options, { theme: theme, data: data.series[0] })); }));
    };
    return TablePanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));



/***/ }),

/***/ "./public/app/plugins/panel/table2/TablePanelEditor.tsx":
/*!**************************************************************!*\
  !*** ./public/app/plugins/panel/table2/TablePanelEditor.tsx ***!
  \**************************************************************/
/*! exports provided: TablePanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TablePanelEditor", function() { return TablePanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");


// Types

var TablePanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TablePanelEditor, _super);
    function TablePanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onToggleShowHeader = function () {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { showHeader: !_this.props.options.showHeader }));
        };
        _this.onToggleFixedHeader = function () {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { fixedHeader: !_this.props.options.fixedHeader }));
        };
        _this.onToggleRotate = function () {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { rotate: !_this.props.options.rotate }));
        };
        _this.onFixedColumnsChange = function (_a) {
            var target = _a.target;
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { fixedColumns: target.value }));
        };
        return _this;
    }
    TablePanelEditor.prototype.render = function () {
        var _a = this.props.options, showHeader = _a.showHeader, fixedHeader = _a.fixedHeader, rotate = _a.rotate, fixedColumns = _a.fixedColumns;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null,
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "section gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", { className: "section-heading" }, "Header"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Show", labelClass: "width-6", checked: showHeader, onChange: this.onToggleShowHeader }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Fixed", labelClass: "width-6", checked: fixedHeader, onChange: this.onToggleFixedHeader })),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "section gf-form-group" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h5", { className: "section-heading" }, "Display"),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Switch"], { label: "Rotate", labelClass: "width-8", checked: rotate, onChange: this.onToggleRotate }),
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["FormField"], { label: "Fixed Columns", labelWidth: 8, inputWidth: 4, type: "number", step: "1", min: "0", max: "100", onChange: this.onFixedColumnsChange, value: fixedColumns }))));
    };
    return TablePanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/table2/module.tsx":
/*!****************************************************!*\
  !*** ./public/app/plugins/panel/table2/module.tsx ***!
  \****************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _TablePanelEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./TablePanelEditor */ "./public/app/plugins/panel/table2/TablePanelEditor.tsx");
/* harmony import */ var _TablePanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TablePanel */ "./public/app/plugins/panel/table2/TablePanel.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/table2/types.ts");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_TablePanel__WEBPACK_IMPORTED_MODULE_2__["TablePanel"]).setDefaults(_types__WEBPACK_IMPORTED_MODULE_3__["defaults"]).setEditor(_TablePanelEditor__WEBPACK_IMPORTED_MODULE_1__["TablePanelEditor"]);


/***/ }),

/***/ "./public/app/plugins/panel/table2/types.ts":
/*!**************************************************!*\
  !*** ./public/app/plugins/panel/table2/types.ts ***!
  \**************************************************/
/*! exports provided: defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
var defaults = {
    showHeader: true,
    fixedHeader: true,
    fixedColumns: 0,
    rotate: false,
    styles: [
        {
            type: 'date',
            pattern: 'Time',
            alias: 'Time',
            dateFormat: 'YYYY-MM-DD HH:mm:ss',
        },
        {
            unit: 'short',
            type: 'number',
            alias: '',
            decimals: 2,
            colors: ['rgba(245, 54, 54, 0.9)', 'rgba(237, 129, 40, 0.89)', 'rgba(50, 172, 45, 0.97)'],
            pattern: '/.*/',
            thresholds: [],
        },
    ],
};


/***/ }),

/***/ "./public/app/plugins/panel/text/module.ts":
/*!*************************************************!*\
  !*** ./public/app/plugins/panel/text/module.ts ***!
  \*************************************************/
/*! exports provided: TextPanelCtrl, PanelCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextPanelCtrl", function() { return TextPanelCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return TextPanelCtrl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var app_plugins_sdk__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/plugins/sdk */ "./public/app/plugins/sdk.ts");
/* harmony import */ var app_core_utils_text__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/core/utils/text */ "./public/app/core/utils/text.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");






var defaultContent = "\n# Title\n\nFor markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)\n\n\n\n";
var TextPanelCtrl = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TextPanelCtrl, _super);
    /** @ngInject */
    function TextPanelCtrl($scope, $injector, templateSrv, $sce) {
        var _this = _super.call(this, $scope, $injector) || this;
        _this.templateSrv = templateSrv;
        _this.$sce = $sce;
        // Set and populate defaults
        _this.panelDefaults = {
            mode: 'markdown',
            content: defaultContent,
        };
        lodash__WEBPACK_IMPORTED_MODULE_1___default.a.defaults(_this.panel, _this.panelDefaults);
        _this.events.on('init-edit-mode', _this.onInitEditMode.bind(_this));
        _this.events.on('refresh', _this.onRefresh.bind(_this));
        _this.events.on('render', _this.onRender.bind(_this));
        var renderWhenChanged = function (scope) {
            var panel = scope.ctrl.panel;
            return [panel.content, panel.mode].join();
        };
        $scope.$watch(renderWhenChanged, lodash__WEBPACK_IMPORTED_MODULE_1___default.a.throttle(function () {
            _this.render();
        }, 100));
        return _this;
    }
    TextPanelCtrl.prototype.onInitEditMode = function () {
        this.addEditorTab('Options', 'public/app/plugins/panel/text/editor.html');
        if (this.panel.mode === 'text') {
            this.panel.mode = 'markdown';
        }
    };
    TextPanelCtrl.prototype.onRefresh = function () {
        this.render();
    };
    TextPanelCtrl.prototype.onRender = function () {
        if (this.panel.mode === 'markdown') {
            this.renderMarkdown(this.panel.content);
        }
        else if (this.panel.mode === 'html') {
            this.updateContent(this.panel.content);
        }
        this.renderingCompleted();
    };
    TextPanelCtrl.prototype.renderText = function (content) {
        var safeContent = Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_3__["escapeHtml"])(content).replace(/\n/g, '<br/>');
        this.updateContent(safeContent);
    };
    TextPanelCtrl.prototype.renderMarkdown = function (content) {
        var _this = this;
        this.$scope.$applyAsync(function () {
            _this.updateContent(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_5__["renderMarkdown"])(content));
        });
    };
    TextPanelCtrl.prototype.updateContent = function (html) {
        html = app_core_config__WEBPACK_IMPORTED_MODULE_4__["default"].disableSanitizeHtml ? html : Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_3__["sanitize"])(html);
        try {
            this.content = this.$sce.trustAsHtml(this.templateSrv.replace(html, this.panel.scopedVars));
        }
        catch (e) {
            console.log('Text panel error: ', e);
            this.content = this.$sce.trustAsHtml(html);
        }
    };
    TextPanelCtrl.templateUrl = "public/app/plugins/panel/text/module.html";
    TextPanelCtrl.scrollable = true;
    return TextPanelCtrl;
}(app_plugins_sdk__WEBPACK_IMPORTED_MODULE_2__["PanelCtrl"]));




/***/ }),

/***/ "./public/app/plugins/panel/text2/TextPanel.tsx":
/*!******************************************************!*\
  !*** ./public/app/plugins/panel/text2/TextPanel.tsx ***!
  \******************************************************/
/*! exports provided: TextPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextPanel", function() { return TextPanel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _grafana_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @grafana/data */ "./packages/grafana-data/src/index.ts");
/* harmony import */ var app_core_utils_text__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/utils/text */ "./public/app/core/utils/text.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");

// Libraries



// Utils


var TextPanel = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TextPanel, _super);
    function TextPanel(props) {
        var _this = _super.call(this, props) || this;
        _this.updateHTML = Object(lodash__WEBPACK_IMPORTED_MODULE_2__["debounce"])(function () {
            var html = _this.processContent(_this.props.options);
            if (html !== _this.state.html) {
                _this.setState({ html: html });
            }
        }, 150);
        _this.state = {
            html: _this.processContent(props.options),
        };
        return _this;
    }
    TextPanel.prototype.componentDidUpdate = function (prevProps) {
        // Since any change could be referenced in a template variable,
        // This needs to process everytime (with debounce)
        this.updateHTML();
    };
    TextPanel.prototype.prepareHTML = function (html) {
        var replaceVariables = this.props.replaceVariables;
        html = app_core_config__WEBPACK_IMPORTED_MODULE_5__["default"].disableSanitizeHtml ? html : Object(app_core_utils_text__WEBPACK_IMPORTED_MODULE_4__["sanitize"])(html);
        return replaceVariables(html);
    };
    TextPanel.prototype.prepareText = function (content) {
        return this.prepareHTML(content
            .replace(/&/g, '&amp;')
            .replace(/>/g, '&gt;')
            .replace(/</g, '&lt;')
            .replace(/\n/g, '<br/>'));
    };
    TextPanel.prototype.prepareMarkdown = function (content) {
        return this.prepareHTML(Object(_grafana_data__WEBPACK_IMPORTED_MODULE_3__["renderMarkdown"])(content));
    };
    TextPanel.prototype.processContent = function (options) {
        var mode = options.mode, content = options.content;
        if (!content) {
            return '';
        }
        if (mode === 'markdown') {
            return this.prepareMarkdown(content);
        }
        if (mode === 'html') {
            return this.prepareHTML(content);
        }
        return this.prepareText(content);
    };
    TextPanel.prototype.render = function () {
        var html = this.state.html;
        return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "markdown-html panel-text-content", dangerouslySetInnerHTML: { __html: html } });
    };
    return TextPanel;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/text2/TextPanelEditor.tsx":
/*!************************************************************!*\
  !*** ./public/app/plugins/panel/text2/TextPanelEditor.tsx ***!
  \************************************************************/
/*! exports provided: TextPanelEditor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextPanelEditor", function() { return TextPanelEditor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries

// Components

var TextPanelEditor = /** @class */ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TextPanelEditor, _super);
    function TextPanelEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.modes = [
            { value: 'markdown', label: 'Markdown' },
            { value: 'text', label: 'Text' },
            { value: 'html', label: 'HTML' },
        ];
        _this.onModeChange = function (item) {
            return _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { mode: item.value }));
        };
        _this.onContentChange = function (evt) {
            _this.props.onOptionsChange(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, _this.props.options, { content: evt.target.value }));
        };
        return _this;
    }
    TextPanelEditor.prototype.render = function () {
        var _a = this.props.options, mode = _a.mode, content = _a.content;
        return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["PanelOptionsGroup"], { title: "Text" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form-inline" },
                react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", { className: "gf-form" },
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", { className: "gf-form-label" }, "Mode"),
                    react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_2__["Select"], { onChange: this.onModeChange, value: this.modes.find(function (e) { return mode === e.value; }), options: this.modes }))),
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("textarea", { value: content, onChange: this.onContentChange, className: "gf-form-input", rows: 10 })));
    };
    return TextPanelEditor;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));



/***/ }),

/***/ "./public/app/plugins/panel/text2/module.tsx":
/*!***************************************************!*\
  !*** ./public/app/plugins/panel/text2/module.tsx ***!
  \***************************************************/
/*! exports provided: plugin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "plugin", function() { return plugin; });
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _TextPanelEditor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./TextPanelEditor */ "./public/app/plugins/panel/text2/TextPanelEditor.tsx");
/* harmony import */ var _TextPanel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TextPanel */ "./public/app/plugins/panel/text2/TextPanel.tsx");
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./public/app/plugins/panel/text2/types.ts");




var plugin = new _grafana_ui__WEBPACK_IMPORTED_MODULE_0__["PanelPlugin"](_TextPanel__WEBPACK_IMPORTED_MODULE_2__["TextPanel"])
    .setDefaults(_types__WEBPACK_IMPORTED_MODULE_3__["defaults"])
    .setEditor(_TextPanelEditor__WEBPACK_IMPORTED_MODULE_1__["TextPanelEditor"])
    .setPanelChangeHandler(function (options, prevPluginId, prevOptions) {
    if (prevPluginId === 'text') {
        return prevOptions;
    }
    return options;
});


/***/ }),

/***/ "./public/app/plugins/panel/text2/types.ts":
/*!*************************************************!*\
  !*** ./public/app/plugins/panel/text2/types.ts ***!
  \*************************************************/
/*! exports provided: defaults */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return defaults; });
var defaults = {
    mode: 'markdown',
    content: "# Title\n\nFor markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)\n\n\n",
};


/***/ }),

/***/ "./public/app/plugins/sdk.ts":
/*!***********************************!*\
  !*** ./public/app/plugins/sdk.ts ***!
  \***********************************/
/*! exports provided: PanelCtrl, MetricsPanelCtrl, QueryCtrl, alertTab, loadPluginCss */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var app_features_panel_panel_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/features/panel/panel_ctrl */ "./public/app/features/panel/panel_ctrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelCtrl", function() { return app_features_panel_panel_ctrl__WEBPACK_IMPORTED_MODULE_0__["PanelCtrl"]; });

/* harmony import */ var app_features_panel_metrics_panel_ctrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/features/panel/metrics_panel_ctrl */ "./public/app/features/panel/metrics_panel_ctrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MetricsPanelCtrl", function() { return app_features_panel_metrics_panel_ctrl__WEBPACK_IMPORTED_MODULE_1__["MetricsPanelCtrl"]; });

/* harmony import */ var app_features_panel_query_ctrl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! app/features/panel/query_ctrl */ "./public/app/features/panel/query_ctrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QueryCtrl", function() { return app_features_panel_query_ctrl__WEBPACK_IMPORTED_MODULE_2__["QueryCtrl"]; });

/* harmony import */ var app_features_alerting_AlertTabCtrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/alerting/AlertTabCtrl */ "./public/app/features/alerting/AlertTabCtrl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "alertTab", function() { return app_features_alerting_AlertTabCtrl__WEBPACK_IMPORTED_MODULE_3__["alertTab"]; });

/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "loadPluginCss", function() { return _grafana_runtime__WEBPACK_IMPORTED_MODULE_4__["loadPluginCss"]; });









/***/ }),

/***/ "./public/app/routes/GrafanaCtrl.ts":
/*!******************************************!*\
  !*** ./public/app/routes/GrafanaCtrl.ts ***!
  \******************************************/
/*! exports provided: GrafanaCtrl, grafanaAppDirective */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GrafanaCtrl", function() { return GrafanaCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grafanaAppDirective", function() { return grafanaAppDirective; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js-exposed");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tether-drop */ "./node_modules/tether-drop/dist/js/drop.js");
/* harmony import */ var tether_drop__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(tether_drop__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");
/* harmony import */ var _grafana_runtime__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @grafana/runtime */ "./packages/grafana-runtime/src/index.ts");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_profiler__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/core/profiler */ "./public/app/core/profiler.ts");
/* harmony import */ var app_core_app_events__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/core/app_events */ "./public/app/core/app_events.ts");
/* harmony import */ var app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! app/features/dashboard/services/TimeSrv */ "./public/app/features/dashboard/services/TimeSrv.ts");
/* harmony import */ var app_core_services_keybindingSrv__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! app/core/services/keybindingSrv */ "./public/app/core/services/keybindingSrv.ts");
/* harmony import */ var app_core_services_AngularLoader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/core/services/AngularLoader */ "./public/app/core/services/AngularLoader.ts");
/* harmony import */ var app_store_configureStore__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! app/store/configureStore */ "./public/app/store/configureStore.ts");
/* harmony import */ var app_core_actions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! app/core/actions */ "./public/app/core/actions/index.ts");
/* harmony import */ var app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! app/features/panel/panellinks/link_srv */ "./public/app/features/panel/panellinks/link_srv.ts");

// Libraries


// @ts-ignore

// Utils and servies













var GrafanaCtrl = /** @class */ (function () {
    /** @ngInject */
    function GrafanaCtrl($scope, utilSrv, $rootScope, contextSrv, bridgeSrv, backendSrv, timeSrv, linkSrv, datasourceSrv, keybindingSrv, angularLoader) {
        // make angular loader service available to react components
        Object(app_core_services_AngularLoader__WEBPACK_IMPORTED_MODULE_12__["setAngularLoader"])(angularLoader);
        Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_5__["setBackendSrv"])(backendSrv);
        Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_5__["setDataSourceSrv"])(datasourceSrv);
        Object(app_features_dashboard_services_TimeSrv__WEBPACK_IMPORTED_MODULE_10__["setTimeSrv"])(timeSrv);
        Object(app_features_panel_panellinks_link_srv__WEBPACK_IMPORTED_MODULE_15__["setLinkSrv"])(linkSrv);
        Object(app_core_services_keybindingSrv__WEBPACK_IMPORTED_MODULE_11__["setKeybindingSrv"])(keybindingSrv);
        var store = Object(app_store_configureStore__WEBPACK_IMPORTED_MODULE_13__["configureStore"])();
        Object(_grafana_runtime__WEBPACK_IMPORTED_MODULE_5__["setLocationSrv"])({
            update: function (opt) {
                store.dispatch(Object(app_core_actions__WEBPACK_IMPORTED_MODULE_14__["updateLocation"])(opt));
            },
        });
        $scope.init = function () {
            $scope.contextSrv = contextSrv;
            $scope.appSubUrl = app_core_config__WEBPACK_IMPORTED_MODULE_6__["default"].appSubUrl;
            $scope._ = lodash__WEBPACK_IMPORTED_MODULE_1___default.a;
            app_core_profiler__WEBPACK_IMPORTED_MODULE_8__["profiler"].init(app_core_config__WEBPACK_IMPORTED_MODULE_6__["default"], $rootScope);
            utilSrv.init();
            bridgeSrv.init();
        };
        $rootScope.colors = _grafana_ui__WEBPACK_IMPORTED_MODULE_4__["colors"];
        $rootScope.onAppEvent = function (name, callback, localScope) {
            var unbind = $rootScope.$on(name, callback);
            var callerScope = this;
            if (callerScope.$id === 1 && !localScope) {
                console.log('warning rootScope onAppEvent called without localscope');
            }
            if (localScope) {
                callerScope = localScope;
            }
            callerScope.$on('$destroy', unbind);
        };
        $rootScope.appEvent = function (name, payload) {
            $rootScope.$emit(name, payload);
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].emit(name, payload);
        };
        $scope.init();
    }
    return GrafanaCtrl;
}());

function setViewModeBodyClass(body, mode) {
    body.removeClass('view-mode--tv');
    body.removeClass('view-mode--kiosk');
    body.removeClass('view-mode--inactive');
    switch (mode) {
        case 'tv': {
            body.addClass('view-mode--tv');
            break;
        }
        // 1 & true for legacy states
        case '1':
        case true: {
            body.addClass('view-mode--kiosk');
            break;
        }
    }
}
/** @ngInject */
function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScope, $location) {
    return {
        restrict: 'E',
        controller: GrafanaCtrl,
        link: function (scope, elem) {
            var body = jquery__WEBPACK_IMPORTED_MODULE_2___default()('body');
            // see https://github.com/zenorocha/clipboard.js/issues/155
            jquery__WEBPACK_IMPORTED_MODULE_2___default.a.fn.modal.Constructor.prototype.enforceFocus = function () { };
            jquery__WEBPACK_IMPORTED_MODULE_2___default()('.preloader').remove();
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].on('toggle-sidemenu-mobile', function () {
                body.toggleClass('sidemenu-open--xs');
            });
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].on('toggle-sidemenu-hidden', function () {
                body.toggleClass('sidemenu-hidden');
            });
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].on('playlist-started', function () {
                elem.toggleClass('view-mode--playlist', true);
            });
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].on('playlist-stopped', function () {
                elem.toggleClass('view-mode--playlist', false);
            });
            // check if we are in server side render
            if (document.cookie.indexOf('renderKey') !== -1) {
                body.addClass('body--phantomjs');
            }
            // tooltip removal fix
            // manage page classes
            var pageClass;
            scope.$on('$routeChangeSuccess', function (evt, data) {
                var e_1, _a;
                if (pageClass) {
                    body.removeClass(pageClass);
                }
                if (data.$$route) {
                    pageClass = data.$$route.pageClass;
                    if (pageClass) {
                        body.addClass(pageClass);
                    }
                }
                // clear body class sidemenu states
                body.removeClass('sidemenu-open--xs');
                jquery__WEBPACK_IMPORTED_MODULE_2___default()('#tooltip, .tooltip').remove();
                // check for kiosk url param
                setViewModeBodyClass(body, data.params.kiosk);
                try {
                    // close all drops
                    for (var _b = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](tether_drop__WEBPACK_IMPORTED_MODULE_3___default.a.drops), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var drop = _c.value;
                        drop.destroy();
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].emit('hide-dash-search');
            });
            // handle kiosk mode
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].on('toggle-kiosk-mode', function (options) {
                var search = $location.search();
                if (options && options.exit) {
                    search.kiosk = '1';
                }
                switch (search.kiosk) {
                    case 'tv': {
                        search.kiosk = true;
                        app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].emit('alert-success', ['Press ESC to exit Kiosk mode']);
                        break;
                    }
                    case '1':
                    case true: {
                        delete search.kiosk;
                        break;
                    }
                    default: {
                        search.kiosk = 'tv';
                    }
                }
                $timeout(function () { return $location.search(search); });
                setViewModeBodyClass(body, search.kiosk);
            });
            // handle in active view state class
            var lastActivity = new Date().getTime();
            var activeUser = true;
            var inActiveTimeLimit = 60 * 5000;
            function checkForInActiveUser() {
                if (!activeUser) {
                    return;
                }
                // only go to activity low mode on dashboard page
                if (!body.hasClass('page-dashboard')) {
                    return;
                }
                if (new Date().getTime() - lastActivity > inActiveTimeLimit) {
                    activeUser = false;
                    body.addClass('view-mode--inactive');
                }
            }
            function userActivityDetected() {
                lastActivity = new Date().getTime();
                if (!activeUser) {
                    activeUser = true;
                    body.removeClass('view-mode--inactive');
                }
            }
            // mouse and keyboard is user activity
            body.mousemove(userActivityDetected);
            body.keydown(userActivityDetected);
            // set useCapture = true to catch event here
            document.addEventListener('wheel', userActivityDetected, { capture: true, passive: true });
            // treat tab change as activity
            document.addEventListener('visibilitychange', userActivityDetected);
            // check every 2 seconds
            setInterval(checkForInActiveUser, 2000);
            app_core_app_events__WEBPACK_IMPORTED_MODULE_9__["default"].on('toggle-view-mode', function () {
                lastActivity = 0;
                checkForInActiveUser();
            });
            // handle document clicks that should hide things
            body.click(function (evt) {
                var target = jquery__WEBPACK_IMPORTED_MODULE_2___default()(evt.target);
                if (target.parents().length === 0) {
                    return;
                }
                // ensure dropdown menu doesn't impact on z-index
                body.find('.dropdown-menu-open').removeClass('dropdown-menu-open');
                // for stuff that animates, slides out etc, clicking it needs to
                // hide it right away
                var clickAutoHide = target.closest('[data-click-hide]');
                if (clickAutoHide.length) {
                    var clickAutoHideParent_1 = clickAutoHide.parent();
                    clickAutoHide.detach();
                    setTimeout(function () {
                        clickAutoHideParent_1.append(clickAutoHide);
                    }, 100);
                }
                // hide search
                if (body.find('.search-container').length > 0) {
                    if (target.parents('.search-results-container, .search-field-wrapper').length === 0) {
                        scope.$apply(function () {
                            scope.appEvent('hide-dash-search');
                        });
                    }
                }
                // hide popovers
                var popover = elem.find('.popover');
                if (popover.length > 0 && target.parents('.graph-legend').length === 0) {
                    popover.hide();
                }
            });
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_7__["default"].directive('grafanaApp', grafanaAppDirective);


/***/ }),

/***/ "./public/app/routes/ReactContainer.tsx":
/*!**********************************************!*\
  !*** ./public/app/routes/ReactContainer.tsx ***!
  \**********************************************/
/*! exports provided: reactContainer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reactContainer", function() { return reactContainer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "./node_modules/react/index.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js");
/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js");
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_store_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/store/store */ "./public/app/store/store.ts");
/* harmony import */ var app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/core/utils/ConfigProvider */ "./public/app/core/utils/ConfigProvider.tsx");
/* harmony import */ var _grafana_ui__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @grafana/ui */ "./packages/grafana-ui/src/index.ts");

// Libraries



// Utils and services




function WrapInProvider(store, Component, props) {
    return (react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react_redux__WEBPACK_IMPORTED_MODULE_3__["Provider"], { store: store },
        react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_grafana_ui__WEBPACK_IMPORTED_MODULE_7__["ErrorBoundaryAlert"], { style: "page" },
            react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Component, tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, props)))));
}
/** @ngInject */
function reactContainer($route, $location, $injector, $rootScope, contextSrv) {
    return {
        restrict: 'E',
        template: '',
        link: function (scope, elem) {
            // Check permissions for this component
            var roles = $route.current.locals.roles;
            if (roles && roles.length) {
                if (!roles.some(function (r) { return contextSrv.hasRole(r); })) {
                    $location.url('/');
                }
            }
            var component = $route.current.locals.component;
            // Dynamic imports return whole module, need to extract default export
            if (component.default) {
                component = component.default;
            }
            var props = {
                $injector: $injector,
                $rootScope: $rootScope,
                $scope: scope,
                $contextSrv: contextSrv,
                routeInfo: $route.current.$$route.routeInfo,
            };
            document.body.classList.add('is-react');
            react_dom__WEBPACK_IMPORTED_MODULE_2___default.a.render(WrapInProvider(app_store_store__WEBPACK_IMPORTED_MODULE_5__["store"], Object(app_core_utils_ConfigProvider__WEBPACK_IMPORTED_MODULE_6__["provideTheme"])(component), props), elem[0]);
            scope.$on('$destroy', function () {
                document.body.classList.remove('is-react');
                react_dom__WEBPACK_IMPORTED_MODULE_2___default.a.unmountComponentAtNode(elem[0]);
            });
        },
    };
}
app_core_core_module__WEBPACK_IMPORTED_MODULE_4__["default"].directive('reactContainer', reactContainer);


/***/ }),

/***/ "./public/app/routes/dashboard_loaders.ts":
/*!************************************************!*\
  !*** ./public/app/routes/dashboard_loaders.ts ***!
  \************************************************/
/*! exports provided: LoadDashboardCtrl, NewDashboardCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadDashboardCtrl", function() { return LoadDashboardCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NewDashboardCtrl", function() { return NewDashboardCtrl; });
/* harmony import */ var app_core_core_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! app/core/core_module */ "./public/app/core/core_module.ts");
/* harmony import */ var app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! app/core/utils/location_util */ "./public/app/core/utils/location_util.ts");


var LoadDashboardCtrl = /** @class */ (function () {
    /** @ngInject */
    function LoadDashboardCtrl($scope, $routeParams, dashboardLoaderSrv, backendSrv, $location, $browser) {
        $scope.appEvent('dashboard-fetch-start');
        if (!$routeParams.uid && !$routeParams.slug) {
            backendSrv.get('/api/dashboards/home').then(function (homeDash) {
                if (homeDash.redirectUri) {
                    var newUrl = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__["default"].stripBaseFromUrl(homeDash.redirectUri);
                    $location.path(newUrl);
                }
                else {
                    var meta = homeDash.meta;
                    meta.canSave = meta.canShare = meta.canStar = false;
                    $scope.initDashboard(homeDash, $scope);
                }
            });
            return;
        }
        // if no uid, redirect to new route based on slug
        if (!($routeParams.type === 'script' || $routeParams.type === 'snapshot') && !$routeParams.uid) {
            // @ts-ignore
            backendSrv.getDashboardBySlug($routeParams.slug).then(function (res) {
                if (res) {
                    $location.path(app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__["default"].stripBaseFromUrl(res.meta.url)).replace();
                }
            });
            return;
        }
        dashboardLoaderSrv.loadDashboard($routeParams.type, $routeParams.slug, $routeParams.uid).then(function (result) {
            if (result.meta.url) {
                var url = app_core_utils_location_util__WEBPACK_IMPORTED_MODULE_1__["default"].stripBaseFromUrl(result.meta.url);
                if (url !== $location.path()) {
                    // replace url to not create additional history items and then return so that initDashboard below isn't executed multiple times.
                    $location.path(url).replace();
                    return;
                }
            }
            result.meta.autofitpanels = $routeParams.autofitpanels;
            result.meta.kiosk = $routeParams.kiosk;
            $scope.initDashboard(result, $scope);
        });
    }
    return LoadDashboardCtrl;
}());

var NewDashboardCtrl = /** @class */ (function () {
    /** @ngInject */
    function NewDashboardCtrl($scope, $routeParams) {
        $scope.initDashboard({
            meta: {
                canStar: false,
                canShare: false,
                isNew: true,
                folderId: Number($routeParams.folderId),
            },
            dashboard: {
                title: 'New dashboard',
                panels: [
                    {
                        type: 'add-panel',
                        gridPos: { x: 0, y: 0, w: 12, h: 9 },
                        title: 'Panel Title',
                    },
                ],
            },
        }, $scope);
    }
    return NewDashboardCtrl;
}());

app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].controller('LoadDashboardCtrl', LoadDashboardCtrl);
app_core_core_module__WEBPACK_IMPORTED_MODULE_0__["default"].controller('NewDashboardCtrl', NewDashboardCtrl);


/***/ }),

/***/ "./public/app/routes/registry.ts":
/*!***************************************!*\
  !*** ./public/app/routes/registry.ts ***!
  \***************************************/
/*! exports provided: applyRouteRegistrationHandlers, addRouteRegistrationHandler */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyRouteRegistrationHandlers", function() { return applyRouteRegistrationHandlers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addRouteRegistrationHandler", function() { return addRouteRegistrationHandler; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");

var handlers = [];
function applyRouteRegistrationHandlers($routeProvider) {
    var e_1, _a;
    try {
        for (var handlers_1 = tslib__WEBPACK_IMPORTED_MODULE_0__["__values"](handlers), handlers_1_1 = handlers_1.next(); !handlers_1_1.done; handlers_1_1 = handlers_1.next()) {
            var handler = handlers_1_1.value;
            handler($routeProvider);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (handlers_1_1 && !handlers_1_1.done && (_a = handlers_1.return)) _a.call(handlers_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
}
function addRouteRegistrationHandler(fn) {
    handlers.push(fn);
}


/***/ }),

/***/ "./public/app/routes/routes.ts":
/*!*************************************!*\
  !*** ./public/app/routes/routes.ts ***!
  \*************************************/
/*! exports provided: setupAngularRoutes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setupAngularRoutes", function() { return setupAngularRoutes; });
/* harmony import */ var _dashboard_loaders__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dashboard_loaders */ "./public/app/routes/dashboard_loaders.ts");
/* harmony import */ var _ReactContainer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ReactContainer */ "./public/app/routes/ReactContainer.tsx");
/* harmony import */ var _registry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./registry */ "./public/app/routes/registry.ts");
/* harmony import */ var app_features_folders_CreateFolderCtrl__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! app/features/folders/CreateFolderCtrl */ "./public/app/features/folders/CreateFolderCtrl.ts");
/* harmony import */ var app_features_folders_FolderDashboardsCtrl__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/features/folders/FolderDashboardsCtrl */ "./public/app/features/folders/FolderDashboardsCtrl.ts");
/* harmony import */ var app_features_manage_dashboards_DashboardImportCtrl__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/manage-dashboards/DashboardImportCtrl */ "./public/app/features/manage-dashboards/DashboardImportCtrl.ts");
/* harmony import */ var app_features_admin_ldap_LdapPage__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/features/admin/ldap/LdapPage */ "./public/app/features/admin/ldap/LdapPage.tsx");
/* harmony import */ var app_core_config__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/core/config */ "./public/app/core/config.ts");
/* harmony import */ var app_types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/types */ "./public/app/types/index.ts");
/* harmony import */ var app_core_components_Login_LoginPage__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/core/components/Login/LoginPage */ "./public/app/core/components/Login/LoginPage.tsx");
/* harmony import */ var _core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../core/components/SafeDynamicImport */ "./public/app/core/components/SafeDynamicImport.tsx");



// Pages





// Types



/** @ngInject */
function setupAngularRoutes($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    // Routes here are guarded both here and server side for react-container routes or just on the server for angular
    // ones. That means angular ones could be navigated to in case there is a client side link some where.
    var importDashboardPage = function () {
        return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(Promise.all(/*! import() | DashboardPage */[__webpack_require__.e("default~DashboardPage~SoloPanelPage"), __webpack_require__.e("DashboardPage")]).then(__webpack_require__.bind(null, /*! ../features/dashboard/containers/DashboardPage */ "./public/app/features/dashboard/containers/DashboardPage.tsx")));
    };
    $routeProvider
        .when('/', {
        template: '<react-container />',
        //@ts-ignore
        pageClass: 'page-dashboard',
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].Home,
        reloadOnSearch: false,
        resolve: {
            component: importDashboardPage,
        },
    })
        .when('/d/:uid/:slug', {
        template: '<react-container />',
        pageClass: 'page-dashboard',
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].Normal,
        reloadOnSearch: false,
        resolve: {
            component: importDashboardPage,
        },
    })
        .when('/d/:uid', {
        template: '<react-container />',
        pageClass: 'page-dashboard',
        reloadOnSearch: false,
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].Normal,
        resolve: {
            component: importDashboardPage,
        },
    })
        .when('/dashboard/:type/:slug', {
        template: '<react-container />',
        pageClass: 'page-dashboard',
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].Normal,
        reloadOnSearch: false,
        resolve: {
            component: importDashboardPage,
        },
    })
        .when('/dashboard/new', {
        template: '<react-container />',
        pageClass: 'page-dashboard',
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].New,
        reloadOnSearch: false,
        resolve: {
            component: importDashboardPage,
        },
    })
        .when('/d-solo/:uid/:slug', {
        template: '<react-container />',
        pageClass: 'dashboard-solo',
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].Normal,
        reloadOnSearch: false,
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(Promise.all(/*! import() | SoloPanelPage */[__webpack_require__.e("default~DashboardPage~SoloPanelPage"), __webpack_require__.e("SoloPanelPage")]).then(__webpack_require__.bind(null, /*! ../features/dashboard/containers/SoloPanelPage */ "./public/app/features/dashboard/containers/SoloPanelPage.tsx")));
            },
        },
    })
        .when('/dashboard-solo/:type/:slug', {
        template: '<react-container />',
        pageClass: 'dashboard-solo',
        routeInfo: app_types__WEBPACK_IMPORTED_MODULE_8__["DashboardRouteInfo"].Normal,
        reloadOnSearch: false,
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(Promise.all(/*! import() | SoloPanelPage */[__webpack_require__.e("default~DashboardPage~SoloPanelPage"), __webpack_require__.e("SoloPanelPage")]).then(__webpack_require__.bind(null, /*! ../features/dashboard/containers/SoloPanelPage */ "./public/app/features/dashboard/containers/SoloPanelPage.tsx")));
            },
        },
    })
        .when('/dashboard/import', {
        templateUrl: 'public/app/features/manage-dashboards/partials/dashboard_import.html',
        controller: app_features_manage_dashboards_DashboardImportCtrl__WEBPACK_IMPORTED_MODULE_5__["default"],
        controllerAs: 'ctrl',
    })
        .when('/datasources', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | DataSourcesListPage */ "DataSourcesListPage").then(__webpack_require__.bind(null, /*! app/features/datasources/DataSourcesListPage */ "./public/app/features/datasources/DataSourcesListPage.tsx")));
            },
        },
    })
        .when('/datasources/edit/:id/', {
        template: '<react-container />',
        reloadOnSearch: false,
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | DataSourceSettingsPage */ "DataSourceSettingsPage").then(__webpack_require__.bind(null, /*! ../features/datasources/settings/DataSourceSettingsPage */ "./public/app/features/datasources/settings/DataSourceSettingsPage.tsx")));
            },
        },
    })
        .when('/datasources/edit/:id/dashboards', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | DataSourceDashboards */ "DataSourceDashboards").then(__webpack_require__.bind(null, /*! app/features/datasources/DataSourceDashboards */ "./public/app/features/datasources/DataSourceDashboards.tsx")));
            },
        },
    })
        .when('/datasources/new', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | NewDataSourcePage */ "NewDataSourcePage").then(__webpack_require__.bind(null, /*! ../features/datasources/NewDataSourcePage */ "./public/app/features/datasources/NewDataSourcePage.tsx")));
            },
        },
    })
        .when('/dashboards', {
        templateUrl: 'public/app/features/manage-dashboards/partials/dashboard_list.html',
        controller: 'DashboardListCtrl',
        controllerAs: 'ctrl',
    })
        .when('/dashboards/folder/new', {
        templateUrl: 'public/app/features/folders/partials/create_folder.html',
        controller: app_features_folders_CreateFolderCtrl__WEBPACK_IMPORTED_MODULE_3__["default"],
        controllerAs: 'ctrl',
    })
        .when('/dashboards/f/:uid/:slug/permissions', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | FolderPermissions */ "FolderPermissions").then(__webpack_require__.bind(null, /*! app/features/folders/FolderPermissions */ "./public/app/features/folders/FolderPermissions.tsx")));
            },
        },
    })
        .when('/dashboards/f/:uid/:slug/settings', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | FolderSettingsPage */ "FolderSettingsPage").then(__webpack_require__.bind(null, /*! app/features/folders/FolderSettingsPage */ "./public/app/features/folders/FolderSettingsPage.tsx")));
            },
        },
    })
        .when('/dashboards/f/:uid/:slug', {
        templateUrl: 'public/app/features/folders/partials/folder_dashboards.html',
        controller: app_features_folders_FolderDashboardsCtrl__WEBPACK_IMPORTED_MODULE_4__["default"],
        controllerAs: 'ctrl',
    })
        .when('/dashboards/f/:uid', {
        templateUrl: 'public/app/features/folders/partials/folder_dashboards.html',
        controller: app_features_folders_FolderDashboardsCtrl__WEBPACK_IMPORTED_MODULE_4__["default"],
        controllerAs: 'ctrl',
    })
        .when('/explore', {
        template: '<react-container />',
        reloadOnSearch: false,
        resolve: {
            roles: function () { return (app_core_config__WEBPACK_IMPORTED_MODULE_7__["default"].viewersCanEdit ? [] : ['Editor', 'Admin']); },
            component: function () { return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | explore */ "explore").then(__webpack_require__.bind(null, /*! app/features/explore/Wrapper */ "./public/app/features/explore/Wrapper.tsx"))); },
        },
    })
        .when('/a/:pluginId/', {
        // Someday * and will get a ReactRouter under that path!
        template: '<react-container />',
        reloadOnSearch: false,
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(Promise.all(/*! import() | AppRootPage */[__webpack_require__.e("PluginPage"), __webpack_require__.e("AppRootPage")]).then(__webpack_require__.bind(null, /*! app/features/plugins/AppRootPage */ "./public/app/features/plugins/AppRootPage.tsx")));
            },
        },
    })
        .when('/org', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | OrgDetailsPage */ "OrgDetailsPage").then(__webpack_require__.bind(null, /*! ../features/org/OrgDetailsPage */ "./public/app/features/org/OrgDetailsPage.tsx")));
            },
        },
    })
        .when('/org/new', {
        templateUrl: 'public/app/features/org/partials/newOrg.html',
        controller: 'NewOrgCtrl',
    })
        .when('/org/users', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | UsersListPage */ "UsersListPage").then(__webpack_require__.bind(null, /*! app/features/users/UsersListPage */ "./public/app/features/users/UsersListPage.tsx")));
            },
        },
    })
        .when('/org/users/invite', {
        templateUrl: 'public/app/features/org/partials/invite.html',
        controller: 'UserInviteCtrl',
        controllerAs: 'ctrl',
    })
        .when('/org/apikeys', {
        template: '<react-container />',
        resolve: {
            roles: function () { return ['Editor', 'Admin']; },
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | ApiKeysPage */ "ApiKeysPage").then(__webpack_require__.bind(null, /*! app/features/api-keys/ApiKeysPage */ "./public/app/features/api-keys/ApiKeysPage.tsx")));
            },
        },
    })
        .when('/org/teams', {
        template: '<react-container />',
        resolve: {
            roles: function () { return (app_core_config__WEBPACK_IMPORTED_MODULE_7__["default"].editorsCanAdmin ? [] : ['Editor', 'Admin']); },
            component: function () { return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | TeamList */ "TeamList").then(__webpack_require__.bind(null, /*! app/features/teams/TeamList */ "./public/app/features/teams/TeamList.tsx"))); },
        },
    })
        .when('/org/teams/new', {
        templateUrl: 'public/app/features/teams/partials/create_team.html',
        controller: 'CreateTeamCtrl',
        controllerAs: 'ctrl',
    })
        .when('/org/teams/edit/:id/:page?', {
        template: '<react-container />',
        resolve: {
            roles: function () { return (app_core_config__WEBPACK_IMPORTED_MODULE_7__["default"].editorsCanAdmin ? [] : ['Admin']); },
            component: function () { return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | TeamPages */ "TeamPages").then(__webpack_require__.bind(null, /*! app/features/teams/TeamPages */ "./public/app/features/teams/TeamPages.tsx"))); },
        },
    })
        .when('/profile', {
        templateUrl: 'public/app/features/profile/partials/profile.html',
        controller: 'ProfileCtrl',
        controllerAs: 'ctrl',
    })
        .when('/profile/password', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! app/features/profile/ChangePasswordPage */ "./public/app/features/profile/ChangePasswordPage.tsx")));
            },
        },
    })
        .when('/profile/select-org', {
        templateUrl: 'public/app/features/org/partials/select_org.html',
        controller: 'SelectOrgCtrl',
    })
        // ADMIN
        .when('/admin', {
        templateUrl: 'public/app/features/admin/partials/admin_home.html',
        controller: 'AdminHomeCtrl',
        controllerAs: 'ctrl',
    })
        .when('/admin/settings', {
        templateUrl: 'public/app/features/admin/partials/settings.html',
        controller: 'AdminSettingsCtrl',
        controllerAs: 'ctrl',
    })
        .when('/admin/users', {
        templateUrl: 'public/app/features/admin/partials/users.html',
        controller: 'AdminListUsersCtrl',
        controllerAs: 'ctrl',
    })
        .when('/admin/users/create', {
        templateUrl: 'public/app/features/admin/partials/new_user.html',
        controller: 'AdminEditUserCtrl',
    })
        .when('/admin/users/edit/:id', {
        templateUrl: 'public/app/features/admin/partials/edit_user.html',
        controller: 'AdminEditUserCtrl',
    })
        .when('/admin/orgs', {
        templateUrl: 'public/app/features/admin/partials/orgs.html',
        controller: 'AdminListOrgsCtrl',
        controllerAs: 'ctrl',
    })
        .when('/admin/orgs/edit/:id', {
        templateUrl: 'public/app/features/admin/partials/edit_org.html',
        controller: 'AdminEditOrgCtrl',
        controllerAs: 'ctrl',
    })
        .when('/admin/stats', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | ServerStats */ "ServerStats").then(__webpack_require__.bind(null, /*! app/features/admin/ServerStats */ "./public/app/features/admin/ServerStats.tsx")));
            },
        },
    })
        .when('/admin/ldap', {
        template: '<react-container />',
        resolve: {
            component: function () { return app_features_admin_ldap_LdapPage__WEBPACK_IMPORTED_MODULE_6__["default"]; },
        },
    })
        // LOGIN / SIGNUP
        .when('/login', {
        template: '<react-container/>',
        resolve: {
            component: function () { return app_core_components_Login_LoginPage__WEBPACK_IMPORTED_MODULE_9__["LoginPage"]; },
        },
        pageClass: 'login-page sidemenu-hidden',
    })
        .when('/invite/:code', {
        templateUrl: 'public/app/partials/signup_invited.html',
        controller: 'InvitedCtrl',
        pageClass: 'sidemenu-hidden',
    })
        .when('/signup', {
        templateUrl: 'public/app/partials/signup_step2.html',
        controller: 'SignUpCtrl',
        pageClass: 'sidemenu-hidden',
    })
        .when('/user/password/send-reset-email', {
        templateUrl: 'public/app/partials/reset_password.html',
        controller: 'ResetPasswordCtrl',
        pageClass: 'sidemenu-hidden',
    })
        .when('/user/password/reset', {
        templateUrl: 'public/app/partials/reset_password.html',
        controller: 'ResetPasswordCtrl',
        pageClass: 'sidemenu-hidden',
    })
        .when('/dashboard/snapshots', {
        templateUrl: 'public/app/features/manage-dashboards/partials/snapshot_list.html',
        controller: 'SnapshotListCtrl',
        controllerAs: 'ctrl',
    })
        .when('/plugins', {
        template: '<react-container />',
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | PluginListPage */ "PluginListPage").then(__webpack_require__.bind(null, /*! app/features/plugins/PluginListPage */ "./public/app/features/plugins/PluginListPage.tsx")));
            },
        },
    })
        .when('/plugins/:pluginId/', {
        template: '<react-container />',
        reloadOnSearch: false,
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | PluginPage */ "PluginPage").then(__webpack_require__.bind(null, /*! ../features/plugins/PluginPage */ "./public/app/features/plugins/PluginPage.tsx")));
            },
        },
    })
        .when('/plugins/:pluginId/page/:slug', {
        templateUrl: 'public/app/features/plugins/partials/plugin_page.html',
        controller: 'AppPageCtrl',
        controllerAs: 'ctrl',
    })
        .when('/styleguide/:page?', {
        controller: 'StyleGuideCtrl',
        controllerAs: 'ctrl',
        templateUrl: 'public/app/features/admin/partials/styleguide.html',
    })
        .when('/alerting', {
        redirectTo: '/alerting/list',
    })
        .when('/alerting/list', {
        template: '<react-container />',
        reloadOnSearch: false,
        resolve: {
            component: function () {
                return Object(_core_components_SafeDynamicImport__WEBPACK_IMPORTED_MODULE_10__["SafeDynamicImport"])(__webpack_require__.e(/*! import() | AlertRuleList */ "AlertRuleList").then(__webpack_require__.bind(null, /*! app/features/alerting/AlertRuleList */ "./public/app/features/alerting/AlertRuleList.tsx")));
            },
        },
    })
        .when('/alerting/notifications', {
        templateUrl: 'public/app/features/alerting/partials/notifications_list.html',
        controller: 'AlertNotificationsListCtrl',
        controllerAs: 'ctrl',
    })
        .when('/alerting/notification/new', {
        templateUrl: 'public/app/features/alerting/partials/notification_edit.html',
        controller: 'AlertNotificationEditCtrl',
        controllerAs: 'ctrl',
    })
        .when('/alerting/notification/:id/edit', {
        templateUrl: 'public/app/features/alerting/partials/notification_edit.html',
        controller: 'AlertNotificationEditCtrl',
        controllerAs: 'ctrl',
    })
        .otherwise({
        templateUrl: 'public/app/partials/error.html',
        controller: 'ErrorCtrl',
    });
    Object(_registry__WEBPACK_IMPORTED_MODULE_2__["applyRouteRegistrationHandlers"])($routeProvider);
}


/***/ }),

/***/ "./public/app/store/configureStore.ts":
/*!********************************************!*\
  !*** ./public/app/store/configureStore.ts ***!
  \********************************************/
/*! exports provided: addRootReducer, configureStore */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addRootReducer", function() { return addRootReducer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "configureStore", function() { return configureStore; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");
/* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! redux */ "./node_modules/redux/es/redux.js");
/* harmony import */ var redux_thunk__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! redux-thunk */ "./node_modules/redux-thunk/es/index.js");
/* harmony import */ var redux_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! redux-logger */ "./node_modules/redux-logger/dist/redux-logger.js");
/* harmony import */ var redux_logger__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(redux_logger__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var app_core_reducers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! app/core/reducers */ "./public/app/core/reducers/index.ts");
/* harmony import */ var app_features_alerting_state_reducers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! app/features/alerting/state/reducers */ "./public/app/features/alerting/state/reducers.ts");
/* harmony import */ var app_features_teams_state_reducers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! app/features/teams/state/reducers */ "./public/app/features/teams/state/reducers.ts");
/* harmony import */ var app_features_api_keys_state_reducers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! app/features/api-keys/state/reducers */ "./public/app/features/api-keys/state/reducers.ts");
/* harmony import */ var app_features_folders_state_reducers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! app/features/folders/state/reducers */ "./public/app/features/folders/state/reducers.ts");
/* harmony import */ var app_features_dashboard_state_reducers__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! app/features/dashboard/state/reducers */ "./public/app/features/dashboard/state/reducers.ts");
/* harmony import */ var app_features_explore_state_reducers__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! app/features/explore/state/reducers */ "./public/app/features/explore/state/reducers.ts");
/* harmony import */ var app_features_plugins_state_reducers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! app/features/plugins/state/reducers */ "./public/app/features/plugins/state/reducers.ts");
/* harmony import */ var app_features_datasources_state_reducers__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! app/features/datasources/state/reducers */ "./public/app/features/datasources/state/reducers.ts");
/* harmony import */ var app_features_users_state_reducers__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! app/features/users/state/reducers */ "./public/app/features/users/state/reducers.ts");
/* harmony import */ var app_features_profile_state_reducers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! app/features/profile/state/reducers */ "./public/app/features/profile/state/reducers.ts");
/* harmony import */ var app_features_org_state_reducers__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! app/features/org/state/reducers */ "./public/app/features/org/state/reducers.ts");
/* harmony import */ var app_features_admin_state_reducers__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! app/features/admin/state/reducers */ "./public/app/features/admin/state/reducers.ts");
/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./store */ "./public/app/store/store.ts");
/* harmony import */ var app_core_middlewares_application__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! app/core/middlewares/application */ "./public/app/core/middlewares/application.ts");



















var rootReducers = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, app_core_reducers__WEBPACK_IMPORTED_MODULE_4__["default"], app_features_alerting_state_reducers__WEBPACK_IMPORTED_MODULE_5__["default"], app_features_teams_state_reducers__WEBPACK_IMPORTED_MODULE_6__["default"], app_features_api_keys_state_reducers__WEBPACK_IMPORTED_MODULE_7__["default"], app_features_folders_state_reducers__WEBPACK_IMPORTED_MODULE_8__["default"], app_features_dashboard_state_reducers__WEBPACK_IMPORTED_MODULE_9__["default"], app_features_explore_state_reducers__WEBPACK_IMPORTED_MODULE_10__["default"], app_features_plugins_state_reducers__WEBPACK_IMPORTED_MODULE_11__["default"], app_features_datasources_state_reducers__WEBPACK_IMPORTED_MODULE_12__["default"], app_features_users_state_reducers__WEBPACK_IMPORTED_MODULE_13__["default"], app_features_profile_state_reducers__WEBPACK_IMPORTED_MODULE_14__["default"], app_features_org_state_reducers__WEBPACK_IMPORTED_MODULE_15__["default"], app_features_admin_state_reducers__WEBPACK_IMPORTED_MODULE_16__["default"]);
function addRootReducer(reducers) {
    Object.assign.apply(Object, tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"]([rootReducers], reducers));
}
function configureStore() {
    var composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || redux__WEBPACK_IMPORTED_MODULE_1__["compose"];
    var rootReducer = Object(redux__WEBPACK_IMPORTED_MODULE_1__["combineReducers"])(rootReducers);
    var logger = Object(redux_logger__WEBPACK_IMPORTED_MODULE_3__["createLogger"])({
        predicate: function (getState) {
            return getState().application.logActions;
        },
    });
    var storeEnhancers =  true
        ? Object(redux__WEBPACK_IMPORTED_MODULE_1__["applyMiddleware"])(app_core_middlewares_application__WEBPACK_IMPORTED_MODULE_18__["toggleLogActionsMiddleware"], redux_thunk__WEBPACK_IMPORTED_MODULE_2__["default"], logger)
        : undefined;
    var store = Object(redux__WEBPACK_IMPORTED_MODULE_1__["createStore"])(rootReducer, {}, composeEnhancers(storeEnhancers));
    Object(_store__WEBPACK_IMPORTED_MODULE_17__["setStore"])(store);
    return store;
}


/***/ }),

/***/ "./public/app/store/store.ts":
/*!***********************************!*\
  !*** ./public/app/store/store.ts ***!
  \***********************************/
/*! exports provided: store, setStore */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "store", function() { return store; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStore", function() { return setStore; });
var store;
function setStore(newStore) {
    store = newStore;
}


/***/ }),

/***/ "./public/app/types/acl.ts":
/*!*********************************!*\
  !*** ./public/app/types/acl.ts ***!
  \*********************************/
/*! exports provided: OrgRole, PermissionLevel, DataSourcePermissionLevel, AclTarget, dataSourceAclLevels, dashboardAclTargets, dashboardPermissionLevels, TeamPermissionLevel, teamsPermissionLevels */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrgRole", function() { return OrgRole; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PermissionLevel", function() { return PermissionLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataSourcePermissionLevel", function() { return DataSourcePermissionLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AclTarget", function() { return AclTarget; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataSourceAclLevels", function() { return dataSourceAclLevels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardAclTargets", function() { return dashboardAclTargets; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dashboardPermissionLevels", function() { return dashboardPermissionLevels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TeamPermissionLevel", function() { return TeamPermissionLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "teamsPermissionLevels", function() { return teamsPermissionLevels; });
var OrgRole;
(function (OrgRole) {
    OrgRole["Viewer"] = "Viewer";
    OrgRole["Editor"] = "Editor";
    OrgRole["Admin"] = "Admin";
})(OrgRole || (OrgRole = {}));
var PermissionLevel;
(function (PermissionLevel) {
    PermissionLevel[PermissionLevel["View"] = 1] = "View";
    PermissionLevel[PermissionLevel["Edit"] = 2] = "Edit";
    PermissionLevel[PermissionLevel["Admin"] = 4] = "Admin";
})(PermissionLevel || (PermissionLevel = {}));
var DataSourcePermissionLevel;
(function (DataSourcePermissionLevel) {
    DataSourcePermissionLevel[DataSourcePermissionLevel["Query"] = 1] = "Query";
    DataSourcePermissionLevel[DataSourcePermissionLevel["Admin"] = 2] = "Admin";
})(DataSourcePermissionLevel || (DataSourcePermissionLevel = {}));
var AclTarget;
(function (AclTarget) {
    AclTarget["Team"] = "Team";
    AclTarget["User"] = "User";
    AclTarget["Viewer"] = "Viewer";
    AclTarget["Editor"] = "Editor";
})(AclTarget || (AclTarget = {}));
var dataSourceAclLevels = [
    { value: DataSourcePermissionLevel.Query, label: 'Query', description: 'Can query data source.' },
];
var dashboardAclTargets = [
    { value: AclTarget.Team, text: 'Team' },
    { value: AclTarget.User, text: 'User' },
    { value: AclTarget.Viewer, text: 'Everyone With Viewer Role' },
    { value: AclTarget.Editor, text: 'Everyone With Editor Role' },
];
var dashboardPermissionLevels = [
    { value: PermissionLevel.View, label: 'View', description: 'Can view dashboards.' },
    { value: PermissionLevel.Edit, label: 'Edit', description: 'Can add, edit and delete dashboards.' },
    {
        value: PermissionLevel.Admin,
        label: 'Admin',
        description: 'Can add/remove permissions and can add, edit and delete dashboards.',
    },
];
var TeamPermissionLevel;
(function (TeamPermissionLevel) {
    TeamPermissionLevel[TeamPermissionLevel["Member"] = 0] = "Member";
    TeamPermissionLevel[TeamPermissionLevel["Admin"] = 4] = "Admin";
})(TeamPermissionLevel || (TeamPermissionLevel = {}));
var teamsPermissionLevels = [
    { value: TeamPermissionLevel.Member, label: 'Member', description: 'Is team member' },
    {
        value: TeamPermissionLevel.Admin,
        label: 'Admin',
        description: 'Can add/remove permissions, members and delete team.',
    },
];


/***/ }),

/***/ "./public/app/types/alerting.ts":
/*!**************************************!*\
  !*** ./public/app/types/alerting.ts ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/apiKeys.ts":
/*!*************************************!*\
  !*** ./public/app/types/apiKeys.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/appNotifications.ts":
/*!**********************************************!*\
  !*** ./public/app/types/appNotifications.ts ***!
  \**********************************************/
/*! exports provided: AppNotificationSeverity, AppNotificationTimeout */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppNotificationSeverity", function() { return AppNotificationSeverity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppNotificationTimeout", function() { return AppNotificationTimeout; });
var AppNotificationSeverity;
(function (AppNotificationSeverity) {
    AppNotificationSeverity["Success"] = "success";
    AppNotificationSeverity["Warning"] = "warning";
    AppNotificationSeverity["Error"] = "error";
    AppNotificationSeverity["Info"] = "info";
})(AppNotificationSeverity || (AppNotificationSeverity = {}));
var AppNotificationTimeout;
(function (AppNotificationTimeout) {
    AppNotificationTimeout[AppNotificationTimeout["Warning"] = 5000] = "Warning";
    AppNotificationTimeout[AppNotificationTimeout["Success"] = 3000] = "Success";
    AppNotificationTimeout[AppNotificationTimeout["Error"] = 7000] = "Error";
})(AppNotificationTimeout || (AppNotificationTimeout = {}));


/***/ }),

/***/ "./public/app/types/dashboard.ts":
/*!***************************************!*\
  !*** ./public/app/types/dashboard.ts ***!
  \***************************************/
/*! exports provided: DashboardRouteInfo, DashboardInitPhase, KIOSK_MODE_TV */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardRouteInfo", function() { return DashboardRouteInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardInitPhase", function() { return DashboardInitPhase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KIOSK_MODE_TV", function() { return KIOSK_MODE_TV; });
var DashboardRouteInfo;
(function (DashboardRouteInfo) {
    DashboardRouteInfo["Home"] = "home-dashboard";
    DashboardRouteInfo["New"] = "new-dashboard";
    DashboardRouteInfo["Normal"] = "normal-dashboard";
    DashboardRouteInfo["Scripted"] = "scripted-dashboard";
})(DashboardRouteInfo || (DashboardRouteInfo = {}));
var DashboardInitPhase;
(function (DashboardInitPhase) {
    DashboardInitPhase["NotStarted"] = "Not started";
    DashboardInitPhase["Fetching"] = "Fetching";
    DashboardInitPhase["Services"] = "Services";
    DashboardInitPhase["Failed"] = "Failed";
    DashboardInitPhase["Completed"] = "Completed";
})(DashboardInitPhase || (DashboardInitPhase = {}));
var KIOSK_MODE_TV = 'tv';


/***/ }),

/***/ "./public/app/types/datasources.ts":
/*!*****************************************!*\
  !*** ./public/app/types/datasources.ts ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/explore.ts":
/*!*************************************!*\
  !*** ./public/app/types/explore.ts ***!
  \*************************************/
/*! exports provided: ExploreMode, CompletionItemKind, ExploreId, LanguageProvider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExploreMode", function() { return ExploreMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExploreId", function() { return ExploreId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageProvider", function() { return LanguageProvider; });
var ExploreMode;
(function (ExploreMode) {
    ExploreMode["Metrics"] = "Metrics";
    ExploreMode["Logs"] = "Logs";
})(ExploreMode || (ExploreMode = {}));
var CompletionItemKind;
(function (CompletionItemKind) {
    CompletionItemKind["GroupTitle"] = "GroupTitle";
})(CompletionItemKind || (CompletionItemKind = {}));
var ExploreId;
(function (ExploreId) {
    ExploreId["left"] = "left";
    ExploreId["right"] = "right";
})(ExploreId || (ExploreId = {}));
var LanguageProvider = /** @class */ (function () {
    function LanguageProvider() {
    }
    return LanguageProvider;
}());



/***/ }),

/***/ "./public/app/types/folders.ts":
/*!*************************************!*\
  !*** ./public/app/types/folders.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/index.ts":
/*!***********************************!*\
  !*** ./public/app/types/index.ts ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _teams__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./teams */ "./public/app/types/teams.ts");
/* harmony import */ var _teams__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_teams__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _teams__WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _teams__WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _alerting__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./alerting */ "./public/app/types/alerting.ts");
/* harmony import */ var _alerting__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_alerting__WEBPACK_IMPORTED_MODULE_1__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _alerting__WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _alerting__WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _location__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./location */ "./public/app/types/location.ts");
/* harmony import */ var _location__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_location__WEBPACK_IMPORTED_MODULE_2__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _location__WEBPACK_IMPORTED_MODULE_2__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _location__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _folders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./folders */ "./public/app/types/folders.ts");
/* harmony import */ var _folders__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_folders__WEBPACK_IMPORTED_MODULE_3__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _folders__WEBPACK_IMPORTED_MODULE_3__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _folders__WEBPACK_IMPORTED_MODULE_3__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _dashboard__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./dashboard */ "./public/app/types/dashboard.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashboardRouteInfo", function() { return _dashboard__WEBPACK_IMPORTED_MODULE_4__["DashboardRouteInfo"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashboardInitPhase", function() { return _dashboard__WEBPACK_IMPORTED_MODULE_4__["DashboardInitPhase"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KIOSK_MODE_TV", function() { return _dashboard__WEBPACK_IMPORTED_MODULE_4__["KIOSK_MODE_TV"]; });

/* harmony import */ var _acl__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./acl */ "./public/app/types/acl.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OrgRole", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["OrgRole"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PermissionLevel", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["PermissionLevel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataSourcePermissionLevel", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["DataSourcePermissionLevel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AclTarget", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["AclTarget"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dataSourceAclLevels", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["dataSourceAclLevels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dashboardAclTargets", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["dashboardAclTargets"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "dashboardPermissionLevels", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["dashboardPermissionLevels"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TeamPermissionLevel", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["TeamPermissionLevel"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "teamsPermissionLevels", function() { return _acl__WEBPACK_IMPORTED_MODULE_5__["teamsPermissionLevels"]; });

/* harmony import */ var _apiKeys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./apiKeys */ "./public/app/types/apiKeys.ts");
/* harmony import */ var _apiKeys__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_apiKeys__WEBPACK_IMPORTED_MODULE_6__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _apiKeys__WEBPACK_IMPORTED_MODULE_6__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _apiKeys__WEBPACK_IMPORTED_MODULE_6__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./user */ "./public/app/types/user.ts");
/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_user__WEBPACK_IMPORTED_MODULE_7__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _user__WEBPACK_IMPORTED_MODULE_7__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _user__WEBPACK_IMPORTED_MODULE_7__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _datasources__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./datasources */ "./public/app/types/datasources.ts");
/* harmony import */ var _datasources__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_datasources__WEBPACK_IMPORTED_MODULE_8__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _datasources__WEBPACK_IMPORTED_MODULE_8__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _datasources__WEBPACK_IMPORTED_MODULE_8__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _plugins__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./plugins */ "./public/app/types/plugins.ts");
/* harmony import */ var _plugins__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_plugins__WEBPACK_IMPORTED_MODULE_9__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _plugins__WEBPACK_IMPORTED_MODULE_9__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _plugins__WEBPACK_IMPORTED_MODULE_9__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _organization__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./organization */ "./public/app/types/organization.ts");
/* harmony import */ var _organization__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_organization__WEBPACK_IMPORTED_MODULE_10__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _organization__WEBPACK_IMPORTED_MODULE_10__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _organization__WEBPACK_IMPORTED_MODULE_10__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _appNotifications__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./appNotifications */ "./public/app/types/appNotifications.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AppNotificationSeverity", function() { return _appNotifications__WEBPACK_IMPORTED_MODULE_11__["AppNotificationSeverity"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AppNotificationTimeout", function() { return _appNotifications__WEBPACK_IMPORTED_MODULE_11__["AppNotificationTimeout"]; });

/* harmony import */ var _search__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./search */ "./public/app/types/search.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DashboardSearchHitType", function() { return _search__WEBPACK_IMPORTED_MODULE_12__["DashboardSearchHitType"]; });

/* harmony import */ var _explore__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./explore */ "./public/app/types/explore.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExploreMode", function() { return _explore__WEBPACK_IMPORTED_MODULE_13__["ExploreMode"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return _explore__WEBPACK_IMPORTED_MODULE_13__["CompletionItemKind"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExploreId", function() { return _explore__WEBPACK_IMPORTED_MODULE_13__["ExploreId"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LanguageProvider", function() { return _explore__WEBPACK_IMPORTED_MODULE_13__["LanguageProvider"]; });

/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./store */ "./public/app/types/store.ts");
/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_store__WEBPACK_IMPORTED_MODULE_14__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _store__WEBPACK_IMPORTED_MODULE_14__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","AppNotificationSeverity","AppNotificationTimeout","DashboardSearchHitType","ExploreMode","CompletionItemKind","ExploreId","LanguageProvider","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _store__WEBPACK_IMPORTED_MODULE_14__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _ldap__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./ldap */ "./public/app/types/ldap.ts");
/* harmony import */ var _ldap__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_ldap__WEBPACK_IMPORTED_MODULE_15__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _ldap__WEBPACK_IMPORTED_MODULE_15__) if(["DashboardRouteInfo","DashboardInitPhase","KIOSK_MODE_TV","OrgRole","PermissionLevel","DataSourcePermissionLevel","AclTarget","dataSourceAclLevels","dashboardAclTargets","dashboardPermissionLevels","TeamPermissionLevel","teamsPermissionLevels","AppNotificationSeverity","AppNotificationTimeout","DashboardSearchHitType","ExploreMode","CompletionItemKind","ExploreId","LanguageProvider","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _ldap__WEBPACK_IMPORTED_MODULE_15__[key]; }) }(__WEBPACK_IMPORT_KEY__));


















/***/ }),

/***/ "./public/app/types/ldap.ts":
/*!**********************************!*\
  !*** ./public/app/types/ldap.ts ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/location.ts":
/*!**************************************!*\
  !*** ./public/app/types/location.ts ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/organization.ts":
/*!******************************************!*\
  !*** ./public/app/types/organization.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/plugins.ts":
/*!*************************************!*\
  !*** ./public/app/types/plugins.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/search.ts":
/*!************************************!*\
  !*** ./public/app/types/search.ts ***!
  \************************************/
/*! exports provided: DashboardSearchHitType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DashboardSearchHitType", function() { return DashboardSearchHitType; });
var DashboardSearchHitType;
(function (DashboardSearchHitType) {
    DashboardSearchHitType["DashHitDB"] = "dash-db";
    DashboardSearchHitType["DashHitHome"] = "dash-home";
    DashboardSearchHitType["DashHitFolder"] = "dash-folder";
})(DashboardSearchHitType || (DashboardSearchHitType = {}));


/***/ }),

/***/ "./public/app/types/store.ts":
/*!***********************************!*\
  !*** ./public/app/types/store.ts ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/teams.ts":
/*!***********************************!*\
  !*** ./public/app/types/teams.ts ***!
  \***********************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/app/types/user.ts":
/*!**********************************!*\
  !*** ./public/app/types/user.ts ***!
  \**********************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/vendor/angular-other/angular-strap.js":
/*!******************************************************!*\
  !*** ./public/vendor/angular-other/angular-strap.js ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/**
 * AngularStrap - Twitter Bootstrap directives for AngularJS
 * @version v0.7.5 - 2013-07-21
 * @link http://mgcrea.github.com/angular-strap
 * @author Olivier Louvignes <olivier@mg-crea.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
angular.module('$strap.config', []).value('$strapConfig', {});
angular.module('$strap.filters', ['$strap.config']);
angular.module('$strap.directives', ['$strap.config']);
angular.module('$strap', [
  '$strap.filters',
  '$strap.directives',
  '$strap.config'
]);
'use strict';
angular.module('$strap.directives').factory('$modal', [
  '$rootScope',
  '$compile',
  '$http',
  '$timeout',
  '$q',
  '$templateCache',
  '$strapConfig',
  function ($rootScope, $compile, $http, $timeout, $q, $templateCache, $strapConfig) {
    var ModalFactory = function ModalFactory(config) {
      function Modal(config) {
        var options = angular.extend({ show: true }, $strapConfig.modal, config);
        var scope = options.scope ? options.scope : $rootScope.$new()
        var templateUrl = options.template;
        return $q.when(options.templateHtml || $templateCache.get(templateUrl) || $http.get(templateUrl, { cache: true }).then(function (res) {
          return res.data;
        })).then(function onSuccess(template) {
          var id = scope.$id;
          if (templateUrl) {
            id += templateUrl.replace('.html', '').replace(/[\/|\.|:]/g, '-');
          }
          // grafana change, removed fade
          var $modal = $('<div class="modal hide" tabindex="-1"></div>').attr('id', id).html(template);
          if (options.modalClass)
            $modal.addClass(options.modalClass);
          $('body').append($modal);
          $timeout(function () {
            $compile($modal)(scope);
          });
          scope.$modal = function (name) {
            $modal.modal(name);
          };
          angular.forEach([
            'show',
            'hide'
          ], function (name) {
            scope[name] = function () {
              $modal.modal(name);
            };
          });
          scope.dismiss = scope.hide;
          angular.forEach([
            'show',
            'shown',
            'hide',
            'hidden'
          ], function (name) {
            $modal.on(name, function (ev) {
              scope.$emit('modal-' + name, ev);
            });
          });
          $modal.on('shown', function (ev) {
            $('input[autofocus], textarea[autofocus]', $modal).first().trigger('focus');
          });
          $modal.on('hidden', function (ev) {
            if (!options.persist)
              scope.$destroy();
          });
          scope.$on('$destroy', function () {
            $modal.remove();
          });
          $modal.modal(options);
          return $modal;
        });
      }
      return new Modal(config);
    };
    return ModalFactory;
  }
])

'use strict';
angular.module('$strap.directives').directive('bsTooltip', [
  '$parse',
  '$compile',
  function ($parse, $compile) {
    return {
      restrict: 'A',
      scope: true,
      link: function postLink(scope, element, attrs, ctrl) {
        var getter = $parse(attrs.bsTooltip), setter = getter.assign, value = getter(scope);
        scope.$watch(attrs.bsTooltip, function (newValue, oldValue) {
          if (newValue !== oldValue) {
            value = newValue;
          }
        });
        // Grafana change, always hide other tooltips
        if (true) {
          element.on('show', function (ev) {
            $('.tooltip.in').each(function () {
              var $this = $(this), tooltip = $this.data('tooltip');
              if (tooltip && !tooltip.$element.is(element)) {
                $this.tooltip('hide');
              }
            });
          });
        }
        element.tooltip({
          title: function () {
            return angular.isFunction(value) ? value.apply(null, arguments) : value;
          },
          html: true,
          container: 'body', // Grafana change
        });
        var tooltip = element.data('tooltip');
        tooltip.show = function () {
          var r = $.fn.tooltip.Constructor.prototype.show.apply(this, arguments);
          this.tip().data('tooltip', this);
          return r;
        };
        scope._tooltip = function (event) {
          element.tooltip(event);
        };
        scope.hide = function () {
          element.tooltip('hide');
        };
        scope.show = function () {
          element.tooltip('show');
        };
        scope.dismiss = scope.hide;
      }
    };
  }
]);

'use strict';
angular.module('$strap.directives').directive('bsTypeahead', [
  '$parse',
  function ($parse) {
    return {
      restrict: 'A',
      require: '?ngModel',
      link: function postLink(scope, element, attrs, controller) {
        var getter = $parse(attrs.bsTypeahead), setter = getter.assign, value = getter(scope);
        scope.$watch(attrs.bsTypeahead, function (newValue, oldValue) {
          if (newValue !== oldValue) {
            value = newValue;
          }
        });
        element.attr('data-provide', 'typeahead');
        element.typeahead({
          source: function (query) {
            return angular.isFunction(value) ? value.apply(null, arguments) : value;
          },
          minLength: attrs.minLength || 1,
          items: attrs.items,
          updater: function (value) {
            if (controller) {
              scope.$apply(function () {
                controller.$setViewValue(value);
              });
            }
            scope.$emit('typeahead-updated', value);
            return value;
          }
        });
        var typeahead = element.data('typeahead');
        typeahead.lookup = function (ev) {
          var items;
          this.query = this.$element.val() || '';
          if (this.query.length < this.options.minLength) {
            return this.shown ? this.hide() : this;
          }
          items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source;
          return items ? this.process(items) : this;
        };
        if (!!attrs.matchAll) {
          typeahead.matcher = function (item) {
            return true;
          };
        }
        if (attrs.minLength === '0') {
          setTimeout(function () {
            element.on('focus', function () {
              element.val().length === 0 && setTimeout(element.typeahead.bind(element, 'lookup'), 200);
            });
          });
        }
      }
    };
  }
]);


/***/ }),

/***/ "./public/vendor/bootstrap/bootstrap.js":
/*!**********************************************!*\
  !*** ./public/vendor/bootstrap/bootstrap.js ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* ===================================================
 * bootstrap-transition.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#transitions
 * ===================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function ($) {

  "use strict"; // jshint ;_;


  /* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
   * ======================================================= */

  $(function () {

    $.support.transition = (function () {

      var transitionEnd = (function () {

        var el = document.createElement('bootstrap')
          , transEndEventNames = {
               'WebkitTransition' : 'webkitTransitionEnd'
            ,  'MozTransition'    : 'transitionend'
            ,  'OTransition'      : 'oTransitionEnd otransitionend'
            ,  'transition'       : 'transitionend'
            }
          , name

        for (name in transEndEventNames){
          if (el.style[name] !== undefined) {
            return transEndEventNames[name]
          }
        }

      }())

      return transitionEnd && {
        end: transitionEnd
      }

    })()

  })

}(window.jQuery);/* ==========================================================
 * bootstrap-alert.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#alerts
 * ==========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function ($) {

  "use strict"; // jshint ;_;

/* ============================================================
 * bootstrap-dropdown.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#dropdowns
 * ============================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */


 /* DROPDOWN CLASS DEFINITION
  * ========================= */

  var toggle = '[data-toggle=dropdown]'
    , Dropdown = function (element) {
        var $el = $(element).on('click.dropdown.data-api', this.toggle)
        $('html').on('click.dropdown.data-api', function () {
          $el.parent().removeClass('open')
        })
      }

  Dropdown.prototype = {

    constructor: Dropdown

  , toggle: function (e) {
      var $this = $(this)
        , $parent
        , isActive

      if ($this.is('.disabled, :disabled')) return

      $parent = getParent($this)

      isActive = $parent.hasClass('open')

      clearMenus()

      if (!isActive) {
        if ('ontouchstart' in document.documentElement) {
          // if mobile we we use a backdrop because click events don't delegate
          $('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
        }
        $parent.toggleClass('open')
      }

      $this.focus()

      return false
    }

  , keydown: function (e) {
      var $this
        , $items
        , $active
        , $parent
        , isActive
        , index

      if (!/(38|40|27)/.test(e.keyCode)) return

      $this = $(this)

      e.preventDefault()
      e.stopPropagation()

      if ($this.is('.disabled, :disabled')) return

      $parent = getParent($this)

      isActive = $parent.hasClass('open')

      if (!isActive || (isActive && e.keyCode == 27)) {
        if (e.which == 27) $parent.find(toggle).focus()
        return $this.click()
      }

      $items = $('[role=menu] li:not(.divider):visible a', $parent)

      if (!$items.length) return

      index = $items.index($items.filter(':focus'))

      if (e.keyCode == 38 && index > 0) index--                                        // up
      if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
      if (!~index) index = 0

      $items
        .eq(index)
        .focus()
    }

  }

  function clearMenus() {
    $('.dropdown-backdrop').remove()
    $(toggle).each(function () {
      getParent($(this)).removeClass('open')
    })
  }

  function getParent($this) {
    var selector = $this.attr('data-target')
      , $parent

    if (!selector) {
      selector = $this.attr('href')
      // grafana backport fix from bootstrap 3
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
    }

    $parent = selector && $(selector)

    if (!$parent || !$parent.length) $parent = $this.parent()

    return $parent
  }


  /* DROPDOWN PLUGIN DEFINITION
   * ========================== */

  var old = $.fn.dropdown

  $.fn.dropdown = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('dropdown')
      if (!data) $this.data('dropdown', (data = new Dropdown(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  $.fn.dropdown.Constructor = Dropdown


 /* DROPDOWN NO CONFLICT
  * ==================== */

  $.fn.dropdown.noConflict = function () {
    $.fn.dropdown = old
    return this
  }


  /* APPLY TO STANDARD DROPDOWN ELEMENTS
   * =================================== */

  $(document)
    .on('click.dropdown.data-api', clearMenus)
    .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
    .on('click.dropdown.data-api'  , toggle, Dropdown.prototype.toggle)
    .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)

}(window.jQuery);
/* =========================================================
 * bootstrap-modal.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#modals
 * =========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */


!function ($) {

  "use strict"; // jshint ;_;


 /* MODAL CLASS DEFINITION
  * ====================== */

  var Modal = function (element, options) {
    this.options = options
    this.$element = $(element)
      .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
    this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
  }

  Modal.prototype = {

      constructor: Modal

    , toggle: function () {
        return this[!this.isShown ? 'show' : 'hide']()
      }

    , show: function () {
        var that = this
          , e = $.Event('show')

        this.$element.trigger(e)

        if (this.isShown || e.isDefaultPrevented()) return

        this.isShown = true

        this.escape()

        this.backdrop(function () {
          var transition = $.support.transition && that.$element.hasClass('fade')

          if (!that.$element.parent().length) {
            that.$element.appendTo(document.body) //don't move modals dom position
          }

          that.$element.show()

          if (transition) {
            that.$element[0].offsetWidth // force reflow
          }

          that.$element
            .addClass('in')
            .attr('aria-hidden', false)

          that.enforceFocus()

          transition ?
            that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) :
            that.$element.focus().trigger('shown')

        })
      }

    , hide: function (e) {
        e && e.preventDefault()

        var that = this

        e = $.Event('hide')

        this.$element.trigger(e)

        if (!this.isShown || e.isDefaultPrevented()) return

        this.isShown = false

        this.escape()

        $(document).off('focusin.modal')

        this.$element
          .removeClass('in')
          .attr('aria-hidden', true)

        $.support.transition && this.$element.hasClass('fade') ?
          this.hideWithTransition() :
          this.hideModal()
      }

    , enforceFocus: function () {
        var that = this
        $(document).on('focusin.modal', function (e) {
          if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
            that.$element.focus()
          }
        })
      }

    , escape: function () {
        var that = this
        if (this.isShown && this.options.keyboard) {
          this.$element.on('keyup.dismiss.modal', function ( e ) {
            e.which == 27 && that.hide()
          })
        } else if (!this.isShown) {
          this.$element.off('keyup.dismiss.modal')
        }
      }

    , hideWithTransition: function () {
        var that = this
          , timeout = setTimeout(function () {
              that.$element.off($.support.transition.end)
              that.hideModal()
            }, 500)

        this.$element.one($.support.transition.end, function () {
          clearTimeout(timeout)
          that.hideModal()
        })
      }

    , hideModal: function () {
        var that = this
        this.$element.hide()
        this.backdrop(function () {
          that.removeBackdrop()
          that.$element.trigger('hidden')
        })
      }

    , removeBackdrop: function () {
        this.$backdrop && this.$backdrop.remove()
        this.$backdrop = null
      }

    , backdrop: function (callback) {
        var that = this
          , animate = this.$element.hasClass('fade') ? 'fade' : ''

        if (this.isShown && this.options.backdrop) {
          var doAnimate = $.support.transition && animate

          this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
            .appendTo(document.body)

          this.$backdrop.click(
            this.options.backdrop == 'static' ?
              $.proxy(this.$element[0].focus, this.$element[0])
            : $.proxy(this.hide, this)
          )

          if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

          this.$backdrop.addClass('in')

          if (!callback) return

          doAnimate ?
            this.$backdrop.one($.support.transition.end, callback) :
            callback()

        } else if (!this.isShown && this.$backdrop) {
          this.$backdrop.removeClass('in')

          $.support.transition && this.$element.hasClass('fade')?
            this.$backdrop.one($.support.transition.end, callback) :
            callback()

        } else if (callback) {
          callback()
        }
      }
  }


 /* MODAL PLUGIN DEFINITION
  * ======================= */

  var old = $.fn.modal

  $.fn.modal = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('modal')
        , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
      if (!data) $this.data('modal', (data = new Modal(this, options)))
      if (typeof option == 'string') data[option]()
      else if (options.show) data.show()
    })
  }

  $.fn.modal.defaults = {
      backdrop: true
    , keyboard: true
    , show: true
  }

  $.fn.modal.Constructor = Modal


 /* MODAL NO CONFLICT
  * ================= */

  $.fn.modal.noConflict = function () {
    $.fn.modal = old
    return this
  }


 /* MODAL DATA-API
  * ============== */

  $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this = $(this)
      , href = $this.attr('href')
      , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
      , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())

    e.preventDefault()

    $target
      .modal(option)
      .one('hide', function () {
        $this.focus()
      })
  })

}(window.jQuery);
/* ===========================================================
 * bootstrap-tooltip.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#tooltips
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ===========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function ($) {

  "use strict"; // jshint ;_;


 /* TOOLTIP PUBLIC CLASS DEFINITION
  * =============================== */

  var Tooltip = function (element, options) {
    this.init('tooltip', element, options)
  }

  Tooltip.prototype = {

    constructor: Tooltip

  , init: function (type, element, options) {
      var eventIn
        , eventOut
        , triggers
        , trigger
        , i

      this.type = type
      this.$element = $(element)
      this.options = this.getOptions(options)
      this.enabled = true

      triggers = this.options.trigger.split(' ')

      for (i = triggers.length; i--;) {
        trigger = triggers[i]
        if (trigger == 'click') {
          this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
        } else if (trigger != 'manual') {
          eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
          eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
          this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
          this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
        }
      }

      this.options.selector ?
        (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
        this.fixTitle()
    }

  , getOptions: function (options) {
      options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)

      if (options.delay && typeof options.delay == 'number') {
        options.delay = {
          show: options.delay
        , hide: options.delay
        }
      }

      return options
    }

  , enter: function (e) {
      var defaults = $.fn[this.type].defaults
        , options = {}
        , self

      this._options && $.each(this._options, function (key, value) {
        if (defaults[key] != value) options[key] = value
      }, this)

      self = $(e.currentTarget)[this.type](options).data(this.type)

      if (!self.options.delay || !self.options.delay.show) return self.show()

      clearTimeout(this.timeout)
      self.hoverState = 'in'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'in') self.show()
      }, self.options.delay.show)
    }

  , leave: function (e) {
      var self = $(e.currentTarget)[this.type](this._options).data(this.type)

      if (this.timeout) clearTimeout(this.timeout)
      if (!self.options.delay || !self.options.delay.hide) return self.hide()

      self.hoverState = 'out'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'out') self.hide()
      }, self.options.delay.hide)
    }

  , show: function () {
      var $tip
        , pos
        , actualWidth
        , actualHeight
        , placement
        , tp
        , e = $.Event('show')

      if (this.hasContent() && this.enabled) {
        this.$element.trigger(e)
        if (e.isDefaultPrevented()) return
        $tip = this.tip()
        this.setContent()

        if (this.options.animation) {
          $tip.addClass('fade')
        }

        placement = typeof this.options.placement == 'function' ?
          this.options.placement.call(this, $tip[0], this.$element[0]) :
          this.options.placement

        $tip
          .detach()
          .css({ top: 0, left: 0, display: 'block' })

        this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

        pos = this.getPosition()

        actualWidth = $tip[0].offsetWidth
        actualHeight = $tip[0].offsetHeight

        switch (placement) {
          case 'bottom':
            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'top':
            tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'left':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
            break
          case 'right':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
            break

          // extend placements (top)
          case 'topLeft':
            tp = {top: pos.top - actualHeight,  left: pos.left + pos.width / 2 - (actualWidth * .10)};
            break;
          case 'topRight':
            tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - (actualWidth * .90)};
            break;

          // extend placements (right)
          case 'rightTop':
            tp = {top: pos.top + pos.height / 2 - (actualHeight *.10), left: pos.left + pos.width};
            break;
          case 'rightBottom':
            tp = {top: pos.top + pos.height / 2 - (actualHeight * .90), left: pos.left + pos.width};
            break;

          // extend placements (bottom)
          case 'bottomLeft':
            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - (actualWidth * .10)};
            break;
          case 'bottomRight':
            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - (actualWidth * .90)};
            break;

          // extend placements (left)
          case 'leftTop':
            tp = {top: pos.top + pos.height / 2 - (actualHeight *.10), left: pos.left - actualWidth};
            break;
          case 'leftBottom':
            tp = {top: pos.top + pos.height / 2 - (actualHeight * .90), left: pos.left - actualWidth};
            break;


        }

        this.applyPlacement(tp, placement)
        this.$element.trigger('shown')
      }
    }

  , applyPlacement: function(offset, placement){
      var $tip = this.tip()
        , width = $tip[0].offsetWidth
        , height = $tip[0].offsetHeight
        , actualWidth
        , actualHeight
        , delta
        , replace

      $tip
        .offset(offset)
        .addClass(placement)
        .addClass('in')

      actualWidth = $tip[0].offsetWidth
      actualHeight = $tip[0].offsetHeight

      if (placement == 'top' && actualHeight != height) {
        offset.top = offset.top + height - actualHeight
        replace = true
      }

      if (placement == 'bottom' || placement == 'top') {
        delta = 0

        if (offset.left < 0){
          delta = offset.left * -2
          offset.left = 0
          $tip.offset(offset)
          actualWidth = $tip[0].offsetWidth
          actualHeight = $tip[0].offsetHeight
        }

        this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
      } else {
        this.replaceArrow(actualHeight - height, actualHeight, 'top')
      }

      if (replace) $tip.offset(offset)
    }

  , replaceArrow: function(delta, dimension, position){
      this
        .arrow()
        .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
    }

  , setContent: function () {
      var $tip = this.tip()
        , title = this.getTitle()

      $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
      $tip.removeClass('fade in top bottom left right')
    }

  , hide: function () {
      var that = this
        , $tip = this.tip()
        , e = $.Event('hide')

      this.$element.trigger(e)
      if (e.isDefaultPrevented()) return

      $tip.removeClass('in')

      function removeWithAnimation() {
        var timeout = setTimeout(function () {
          $tip.off($.support.transition.end).detach()
        }, 500)

        $tip.one($.support.transition.end, function () {
          clearTimeout(timeout)
          $tip.detach()
        })
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        removeWithAnimation() :
        $tip.detach()

      this.$element.trigger('hidden')

      return this
    }

  , fixTitle: function () {
      var $e = this.$element
      if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
        $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
      }
    }

  , hasContent: function () {
      return this.getTitle()
    }

  , getPosition: function () {
      var el = this.$element[0]
      return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
        width: el.offsetWidth
      , height: el.offsetHeight
      }, this.$element.offset())
    }

  , getTitle: function () {
      var title
        , $e = this.$element
        , o = this.options

      title = $e.attr('data-original-title')
        || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

      return title
    }

  , tip: function () {
      return this.$tip = this.$tip || $(this.options.template)
    }

  , arrow: function(){
      return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
    }

  , validate: function () {
      if (!this.$element[0].parentNode) {
        this.hide()
        this.$element = null
        this.options = null
      }
    }

  , enable: function () {
      this.enabled = true
    }

  , disable: function () {
      this.enabled = false
    }

  , toggleEnabled: function () {
      this.enabled = !this.enabled
    }

  , toggle: function (e) {
      var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
      self.tip().hasClass('in') ? self.hide() : self.show()
    }

  , destroy: function () {
      this.hide().$element.off('.' + this.type).removeData(this.type)
    }

  }


 /* TOOLTIP PLUGIN DEFINITION
  * ========================= */

  var old = $.fn.tooltip

  $.fn.tooltip = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tooltip')
        , options = typeof option == 'object' && option
      if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tooltip.Constructor = Tooltip

  $.fn.tooltip.defaults = {
    animation: true
  , placement: 'top'
  , selector: false
  , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
  , trigger: 'hover focus'
  , title: ''
  , delay: 0
  , html: false
  , container: false
  }


 /* TOOLTIP NO CONFLICT
  * =================== */

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(window.jQuery);

/* ========================================================
 * bootstrap-tab.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#tabs
 * ========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================== */


!function ($) {

  "use strict"; // jshint ;_;


 /* TAB CLASS DEFINITION
  * ==================== */

  var Tab = function (element) {
    this.element = $(element)
  }

  Tab.prototype = {

    constructor: Tab

  , show: function () {
      var $this = this.element
        , $ul = $this.closest('ul:not(.dropdown-menu)')
        , selector = $this.attr('data-target')
        , previous
        , $target
        , e

      if (!selector) {
        selector = $this.attr('href')
        selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
      }

      if ( $this.parent('li').hasClass('active') ) return

      previous = $ul.find('.active:last a')[0]

      e = $.Event('show', {
        relatedTarget: previous
      })

      $this.trigger(e)

      if (e.isDefaultPrevented()) return

      $target = $(selector)

      this.activate($this.parent('li'), $ul)
      this.activate($target, $target.parent(), function () {
        $this.trigger({
          type: 'shown'
        , relatedTarget: previous
        })
      })
    }

  , activate: function ( element, container, callback) {
      var $active = container.find('> .active')
        , transition = callback
            && $.support.transition
            && $active.hasClass('fade')

      function next() {
        $active
          .removeClass('active')
          .find('> .dropdown-menu > .active')
          .removeClass('active')

        element.addClass('active')

        if (transition) {
          element[0].offsetWidth // reflow for transition
          element.addClass('in')
        } else {
          element.removeClass('fade')
        }

        if ( element.parent('.dropdown-menu') ) {
          element.closest('li.dropdown').addClass('active')
        }

        callback && callback()
      }

      transition ?
        $active.one($.support.transition.end, next) :
        next()

      $active.removeClass('in')
    }
  }


 /* TAB PLUGIN DEFINITION
  * ===================== */

  var old = $.fn.tab

  $.fn.tab = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tab')
      if (!data) $this.data('tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tab.Constructor = Tab


 /* TAB NO CONFLICT
  * =============== */

  $.fn.tab.noConflict = function () {
    $.fn.tab = old
    return this
  }


 /* TAB DATA-API
  * ============ */

  $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
    e.preventDefault()
    $(this).tab('show')
  })

}(window.jQuery);/* =============================================================
 * bootstrap-typeahead.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#typeahead
 * =============================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */


!function($){

  "use strict"; // jshint ;_;


 /* TYPEAHEAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Typeahead = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
    this.updater = this.options.updater || this.updater
    this.source = this.options.source
    this.$menu = $(this.options.menu)
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , select: function () {
    // CHANGE (rashidkpc) If nothing is selected, use existing value
      var val = this.$menu.find('.active').attr('data-value') || this.$element.val();
      this.$element
        .val(this.updater(val))
        .change()
      return this.hide()
    }

  , updater: function (item) {
      return item
    }

  , show: function () {
      var pos = $.extend({}, this.$element.position(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu
        .insertAfter(this.$element)
        .css({
          top: pos.top + pos.height
        , left: pos.left
        })
        .show()

      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var items

      this.query = this.$element.val()

      if (!this.query || this.query.length < this.options.minLength) {
        return this.shown ? this.hide() : this
      }

      items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source

      return items ? this.process(items) : this
    }

    , process: function (items) {
      var that = this

      items = $.grep(items, function (item) {
        return that.matcher(item)
      })

      items = this.sorter(items)

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , highlighter: function (item) {
      var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
      if (!query) {
        return item;
      }
      return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
        return '<strong>' + match + '</strong>'
      });
    }

  , render: function (items) {
      var that = this

      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        return i[0]
      })

      // CHANGE (rashidpc) Do not select first element by default
      // items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev()

      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
    }

  , listen: function () {
      this.$element
        .on('focus',    $.proxy(this.focus, this))
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if (this.eventSupported('keydown')) {
        this.$element.on('keydown', $.proxy(this.keydown, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
    },

    destroy: function () {
      this.$element.off().removeData('typeahead');
      this.$menu.off();
    }

  , eventSupported: function(eventName) {
      var isSupported = eventName in this.$element
      if (!isSupported) {
        this.$element.setAttribute(eventName, 'return;')
        isSupported = typeof this.$element[eventName] === 'function'
      }
      return isSupported
    }

  , move: function (e) {
      if (!this.shown) return

      // grafana change, shift+left parenthesis
      if (e.shiftKey && e.keyCode === 40) {
        return;
      }

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          e.preventDefault()
          this.next()
          break
      }

      e.stopPropagation()
    }

  , keydown: function (e) {
      this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27,57])
      this.move(e)
    }

  , keypress: function (e) {
      if (this.suppressKeyPressRepeat) return
      this.move(e)
    }

  , keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
        case 16: // shift
        case 17: // ctrl
        case 18: // alt
          break

        case 9: // tab
        case 13: // enter
          if (!this.shown) return
          this.select()
          break

        case 27: // escape
          if (!this.shown) return
          this.hide()
          break

        default:
          this.lookup();
      }

      if(e.keyCode === 13 && typeof this.$menu.find('.active').attr('data-value') === 'undefined') {
        // CHANGE (rashidkpc). Enter was hit, nothing was selected from typeahead, submit form
        this.$element.submit();
      } else {
        e.stopPropagation()
        e.preventDefault()
      }

  }

  , focus: function (e) {
      this.focused = true
    }

  , blur: function (e) {
      this.focused = false
      if (!this.mousedover && this.shown) this.hide()
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
      this.$element.focus()
    }

  , mouseenter: function (e) {
      this.mousedover = true
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }

  , mouseleave: function (e) {
      this.mousedover = false
      if (!this.focused && this.shown) this.hide()
    }

  }


  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  var old = $.fn.typeahead

  $.fn.typeahead = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    source: []
  , items: 8
  , menu: '<ul class="typeahead dropdown-menu"></ul>'
  , item: '<li><a href="#"></a></li>'
  , minLength: 1
  }

  $.fn.typeahead.Constructor = Typeahead


 /* TYPEAHEAD NO CONFLICT
  * =================== */

  $.fn.typeahead.noConflict = function () {
    $.fn.typeahead = old
    return this
  }


 /* TYPEAHEAD DATA-API
  * ================== */

  $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
    var $this = $(this)
    if ($this.data('typeahead')) return
    $this.typeahead($this.data())
  })

}(window.jQuery);
/* ==========================================================
 * bootstrap-affix.js v2.3.2
 * http://getbootstrap.com/2.3.2/javascript.html#affix
 * ==========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function ($) {

  "use strict"; // jshint ;_;


 /* AFFIX CLASS DEFINITION
  * ====================== */

  var Affix = function (element, options) {
    this.options = $.extend({}, $.fn.affix.defaults, options)
    this.$window = $(window)
      .on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.affix.data-api',  $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this))
    this.$element = $(element)
    this.checkPosition()
  }

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var scrollHeight = $(document).height()
      , scrollTop = this.$window.scrollTop()
      , position = this.$element.offset()
      , offset = this.options.offset
      , offsetBottom = offset.bottom
      , offsetTop = offset.top
      , reset = 'affix affix-top affix-bottom'
      , affix

    if (typeof offset != 'object') offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function') offsetTop = offset.top()
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()

    affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ?
      false    : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ?
      'bottom' : offsetTop != null && scrollTop <= offsetTop ?
      'top'    : false

    if (this.affixed === affix) return

    this.affixed = affix
    this.unpin = affix == 'bottom' ? position.top - scrollTop : null

    this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''))
  }


 /* AFFIX PLUGIN DEFINITION
  * ======================= */

  var old = $.fn.affix

  $.fn.affix = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('affix')
        , options = typeof option == 'object' && option
      if (!data) $this.data('affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.affix.Constructor = Affix

  $.fn.affix.defaults = {
    offset: 0
  }


 /* AFFIX NO CONFLICT
  * ================= */

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  }


 /* AFFIX DATA-API
  * ============== */

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
        , data = $spy.data()

      data.offset = data.offset || {}

      data.offsetBottom && (data.offset.bottom = data.offsetBottom)
      data.offsetTop && (data.offset.top = data.offsetTop)

      $spy.affix(data)
    })
  })


}(window.jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.crosshair.js":
/*!*****************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.crosshair.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* Flot plugin for showing crosshairs when the mouse hovers over the plot.

Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.

The plugin supports these options:

	crosshair: {
		mode: null or "x" or "y" or "xy"
		color: color
		lineWidth: number
	}

Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
crosshair that lets you trace the values on the x axis, "y" enables a
horizontal crosshair and "xy" enables them both. "color" is the color of the
crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
the drawn lines (default is 1).

The plugin also adds four public methods:

  - setCrosshair( pos )

    Set the position of the crosshair. Note that this is cleared if the user
    moves the mouse. "pos" is in coordinates of the plot and should be on the
    form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
    axes), which is coincidentally the same format as what you get from a
    "plothover" event. If "pos" is null, the crosshair is cleared.

  - clearCrosshair()

    Clear the crosshair.

  - lockCrosshair(pos)

    Cause the crosshair to lock to the current location, no longer updating if
    the user moves the mouse. Optionally supply a position (passed on to
    setCrosshair()) to move it to.

    Example usage:

	var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
	$("#graph").bind( "plothover", function ( evt, position, item ) {
		if ( item ) {
			// Lock the crosshair to the data point being hovered
			myFlot.lockCrosshair({
				x: item.datapoint[ 0 ],
				y: item.datapoint[ 1 ]
			});
		} else {
			// Return normal crosshair operation
			myFlot.unlockCrosshair();
		}
	});

  - unlockCrosshair()

    Free the crosshair to move again after locking it.
*/

(function ($) {
    var options = {
        crosshair: {
            mode: null, // one of null, "x", "y" or "xy",
            color: "rgba(170, 0, 0, 0.80)",
            lineWidth: 1
        }
    };
    
    function init(plot) {
        // position of crosshair in pixels
        var crosshair = { x: -1, y: -1, locked: false };

        plot.setCrosshair = function setCrosshair(pos) {
            if (!pos)
                crosshair.x = -1;
            else {
                var o = plot.p2c(pos);
                crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
                crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
            }
            
            plot.triggerRedrawOverlay();
        };
        
        plot.clearCrosshair = plot.setCrosshair; // passes null for pos
        
        plot.lockCrosshair = function lockCrosshair(pos) {
            if (pos)
                plot.setCrosshair(pos);
            crosshair.locked = true;
        };

        plot.unlockCrosshair = function unlockCrosshair() {
            crosshair.locked = false;
        };

        function onMouseOut(e) {
            if (crosshair.locked)
                return;

            if (crosshair.x != -1) {
                crosshair.x = -1;
                plot.triggerRedrawOverlay();
            }
        }

        function onMouseMove(e) {
            if (crosshair.locked)
                return;
                
            if (plot.getSelection && plot.getSelection()) {
                crosshair.x = -1; // hide the crosshair while selecting
                return;
            }
                
            var offset = plot.offset();
            crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
            crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
            plot.triggerRedrawOverlay();
        }
        
        plot.hooks.bindEvents.push(function (plot, eventHolder) {
            if (!plot.getOptions().crosshair.mode)
                return;

            eventHolder.mouseout(onMouseOut);
            eventHolder.mousemove(onMouseMove);
        });

        plot.hooks.drawOverlay.push(function (plot, ctx) {
            var c = plot.getOptions().crosshair;
            if (!c.mode)
                return;

            var plotOffset = plot.getPlotOffset();
            
            ctx.save();
            ctx.translate(plotOffset.left, plotOffset.top);

            if (crosshair.x != -1) {
                var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;

                ctx.strokeStyle = c.color;
                ctx.lineWidth = c.lineWidth;
                ctx.lineJoin = "round";

                ctx.beginPath();
                if (c.mode.indexOf("x") != -1) {
                    var drawX = Math.floor(crosshair.x) + adj;
                    ctx.moveTo(drawX, 0);
                    ctx.lineTo(drawX, plot.height());
                }
                if (c.mode.indexOf("y") != -1) {
                    var drawY = Math.floor(crosshair.y) + adj;
                    ctx.moveTo(0, drawY);
                    ctx.lineTo(plot.width(), drawY);
                }
                ctx.stroke();
            }
            ctx.restore();
        });

        plot.hooks.shutdown.push(function (plot, eventHolder) {
            eventHolder.unbind("mouseout", onMouseOut);
            eventHolder.unbind("mousemove", onMouseMove);
        });
    }
    
    $.plot.plugins.push({
        init: init,
        options: options,
        name: 'crosshair',
        version: '1.0'
    });
})(jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.dashes.js":
/*!**************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.dashes.js ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/*
 * jQuery.flot.dashes
 *
 * options = {
 *   series: {
 *     dashes: {
 *
 *       // show
 *       // default: false
 *       // Whether to show dashes for the series.
 *       show: <boolean>,
 *
 *       // lineWidth
 *       // default: 2
 *       // The width of the dashed line in pixels.
 *       lineWidth: <number>,
 *
 *       // dashLength
 *       // default: 10
 *       // Controls the length of the individual dashes and the amount of
 *       // space between them.
 *       // If this is a number, the dashes and spaces will have that length.
 *       // If this is an array, it is read as [ dashLength, spaceLength ]
 *       dashLength: <number> or <array[2]>
 *     }
 *   }
 * }
 */
(function($){

  function init(plot) {

    plot.hooks.processDatapoints.push(function(plot, series, datapoints) {

      if (!series.dashes.show) return;

      plot.hooks.draw.push(function(plot, ctx) {

        var plotOffset = plot.getPlotOffset(),
          axisx = series.xaxis,
          axisy = series.yaxis;

        function plotDashes(xoffset, yoffset) {

          var points = datapoints.points,
            ps = datapoints.pointsize,
            prevx = null,
            prevy = null,
            dashRemainder = 0,
            dashOn = true,
            dashOnLength,
            dashOffLength;

          if (series.dashes.dashLength[0]) {
            dashOnLength = series.dashes.dashLength[0];
            if (series.dashes.dashLength[1]) {
              dashOffLength = series.dashes.dashLength[1];
            } else {
              dashOffLength = dashOnLength;
            }
          } else {
            dashOffLength = dashOnLength = series.dashes.dashLength;
          }

          ctx.beginPath();

          for (var i = ps; i < points.length; i += ps) {

            var x1 = points[i - ps],
              y1 = points[i - ps + 1],
              x2 = points[i],
              y2 = points[i + 1];

            if (x1 == null || x2 == null) continue;

            // clip with ymin
            if (y1 <= y2 && y1 < axisy.min) {
              if (y2 < axisy.min) continue;   // line segment is outside
              // compute new intersection point
              x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
              y1 = axisy.min;
            } else if (y2 <= y1 && y2 < axisy.min) {
              if (y1 < axisy.min) continue;
              x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
              y2 = axisy.min;
            }

            // clip with ymax
            if (y1 >= y2 && y1 > axisy.max) {
              if (y2 > axisy.max) continue;
              x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
              y1 = axisy.max;
            } else if (y2 >= y1 && y2 > axisy.max) {
              if (y1 > axisy.max) continue;
              x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
              y2 = axisy.max;
            }

            // clip with xmin
            if (x1 <= x2 && x1 < axisx.min) {
              if (x2 < axisx.min) continue;
              y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
              x1 = axisx.min;
            } else if (x2 <= x1 && x2 < axisx.min) {
              if (x1 < axisx.min) continue;
              y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
              x2 = axisx.min;
            }

            // clip with xmax
            if (x1 >= x2 && x1 > axisx.max) {
              if (x2 > axisx.max) continue;
              y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
              x1 = axisx.max;
            } else if (x2 >= x1 && x2 > axisx.max) {
              if (x1 > axisx.max) continue;
              y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
              x2 = axisx.max;
            }

            if (x1 != prevx || y1 != prevy) {
              ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
            }

            var ax1 = axisx.p2c(x1) + xoffset,
              ay1 = axisy.p2c(y1) + yoffset,
              ax2 = axisx.p2c(x2) + xoffset,
              ay2 = axisy.p2c(y2) + yoffset,
              dashOffset;

            function lineSegmentOffset(segmentLength) {

              var c = Math.sqrt(Math.pow(ax2 - ax1, 2) + Math.pow(ay2 - ay1, 2));

              if (c <= segmentLength) {
                return {
                  deltaX: ax2 - ax1,
                  deltaY: ay2 - ay1,
                  distance: c,
                  remainder: segmentLength - c
                }
              } else {
                var xsign = ax2 > ax1 ? 1 : -1,
                  ysign = ay2 > ay1 ? 1 : -1;
                return {
                  deltaX: xsign * Math.sqrt(Math.pow(segmentLength, 2) / (1 + Math.pow((ay2 - ay1)/(ax2 - ax1), 2))),
                  deltaY: ysign * Math.sqrt(Math.pow(segmentLength, 2) - Math.pow(segmentLength, 2) / (1 + Math.pow((ay2 - ay1)/(ax2 - ax1), 2))),
                  distance: segmentLength,
                  remainder: 0
                };
              }
            }
            //-end lineSegmentOffset

            do {

              dashOffset = lineSegmentOffset(
                dashRemainder > 0 ? dashRemainder :
                  dashOn ? dashOnLength : dashOffLength);

              if (dashOffset.deltaX != 0 || dashOffset.deltaY != 0) {
                if (dashOn) {
                  ctx.lineTo(ax1 + dashOffset.deltaX, ay1 + dashOffset.deltaY);
                } else {
                  ctx.moveTo(ax1 + dashOffset.deltaX, ay1 + dashOffset.deltaY);
                }
              }

              dashOn = !dashOn;
              dashRemainder = dashOffset.remainder;
              ax1 += dashOffset.deltaX;
              ay1 += dashOffset.deltaY;

            } while (dashOffset.distance > 0);

            prevx = x2;
            prevy = y2;
          }

          ctx.stroke();
        }
        //-end plotDashes

        ctx.save();
        ctx.translate(plotOffset.left, plotOffset.top);
        ctx.lineJoin = 'round';

        var lw = series.dashes.lineWidth,
          sw = series.shadowSize;

        // FIXME: consider another form of shadow when filling is turned on
        if (lw > 0 && sw > 0) {
          // draw shadow as a thick and thin line with transparency
          ctx.lineWidth = sw;
          ctx.strokeStyle = "rgba(0,0,0,0.1)";
          // position shadow at angle from the mid of line
          var angle = Math.PI/18;
          plotDashes(Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2));
          ctx.lineWidth = sw/2;
          plotDashes(Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4));
        }

        ctx.lineWidth = lw;
        ctx.strokeStyle = series.color;

        if (lw > 0) {
          plotDashes(0, 0);
        }

        ctx.restore();

      });
      //-end draw hook

    });
    //-end processDatapoints hook

  }
  //-end init

  $.plot.plugins.push({
    init: init,
    options: {
      series: {
        dashes: {
          show: false,
          lineWidth: 2,
          dashLength: 10
        }
      }
    },
    name: 'dashes',
    version: '0.1'
  });

})(jQuery)


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.fillbelow.js":
/*!*****************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.fillbelow.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

(function($) {
    "use strict";

    var options = {
        series: {
            fillBelowTo: null
        }
    };

    function init(plot) {
        function findBelowSeries( series, allseries ) {

            var i;

            for ( i = 0; i < allseries.length; ++i ) {
                if ( allseries[ i ].id === series.fillBelowTo ) {
                    return allseries[ i ];
                }
            }

            return null;
        }

        /* top and bottom doesn't actually matter for this, we're just using it to help make this easier to think about */
        /* this is a vector cross product operation */
        function segmentIntersection(top_left_x, top_left_y, top_right_x, top_right_y, bottom_left_x, bottom_left_y, bottom_right_x, bottom_right_y) {
            var top_delta_x, top_delta_y, bottom_delta_x, bottom_delta_y,
                s, t;

            top_delta_x = top_right_x - top_left_x;
            top_delta_y = top_right_y - top_left_y;
            bottom_delta_x = bottom_right_x - bottom_left_x;
            bottom_delta_y = bottom_right_y - bottom_left_y;

            s = (
                (-top_delta_y * (top_left_x - bottom_left_x)) + (top_delta_x * (top_left_y - bottom_left_y))
            ) / (
                -bottom_delta_x * top_delta_y + top_delta_x * bottom_delta_y
            );

            t = (
                (bottom_delta_x * (top_left_y - bottom_left_y)) - (bottom_delta_y * (top_left_x - bottom_left_x))
            ) / (
                -bottom_delta_x * top_delta_y + top_delta_x * bottom_delta_y
            );

            // Collision detected
            if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
                return [
                    top_left_x + (t * top_delta_x), // X
                    top_left_y + (t * top_delta_y) // Y
                ];
            }

            // No collision
            return null;
        }

        function plotDifferenceArea(plot, ctx, series) {
            if ( series.fillBelowTo === null ) {
                return;
            }

            var otherseries,

                ps,
                points,

                otherps,
                otherpoints,

                plotOffset,
                fillStyle;

            function openPolygon(x, y) {
                ctx.beginPath();
                ctx.moveTo(
                    series.xaxis.p2c(x) + plotOffset.left,
                    series.yaxis.p2c(y) + plotOffset.top
                );

            }

            function closePolygon() {
                ctx.closePath();
                ctx.fill();
            }

            function validateInput() {
                if (points.length/ps !== otherpoints.length/otherps) {
                    console.error("Refusing to graph inconsistent number of points");
                    return false;
                }

                var i;
                for (i = 0; i < (points.length / ps); i++) {
                    if (
                        points[i * ps] !== null &&
                        otherpoints[i * otherps] !== null &&
                        points[i * ps] !== otherpoints[i * otherps]
                    ) {
                        console.error("Refusing to graph points without matching value");
                        return false;
                    }
                }

                return true;
            }

            function findNextStart(start_i, end_i) {
                console.assert(end_i > start_i, "expects the end index to be greater than the start index");

                var start = (
                        start_i === 0 ||
                        points[start_i - 1] === null ||
                        otherpoints[start_i - 1] === null
                    ),
                    equal = false,
                    i,
                    intersect;

                for (i = start_i; i < end_i; i++) {
                    // Take note of null points
                    if (
                        points[(i * ps) + 1] === null ||
                        otherpoints[(i * ps) + 1] === null
                    ) {
                        equal = false;
                        start = true;
                    }

                    // Take note of equal points
                    else if (points[(i * ps) + 1] === otherpoints[(i * otherps) + 1]) {
                        equal = true;
                        start = false;
                    }


                    else if (points[(i * ps) + 1] > otherpoints[(i * otherps) + 1]) {
                        // If we begin above the desired point
                        if (start) {
                            openPolygon(points[i * ps], points[(i * ps) + 1]);
                        }

                        // If an equal point preceeds this, start the polygon at that equal point
                        else if (equal) {
                            openPolygon(points[(i - 1) * ps], points[((i - 1) * ps) + 1]);
                        }

                        // Otherwise, find the intersection point, and start it there
                        else {
                            intersect = intersectionPoint(i);
                            openPolygon(intersect[0], intersect[1]);
                        }

                        topTraversal(i, end_i);
                        return;
                    }

                    // If we go below equal, equal at any preceeding point is irrelevant
                    else {
                        start = false;
                        equal = false;
                    }
                }
            }

            function intersectionPoint(right_i) {
                console.assert(right_i > 0, "expects the second point in the series line segment");

                var i, intersect;

                for (i = 1; i < (otherpoints.length/otherps); i++) {
                    intersect = segmentIntersection(
                        points[(right_i - 1) * ps], points[((right_i - 1) * ps) + 1],
                        points[right_i * ps], points[(right_i * ps) + 1],

                        otherpoints[(i - 1) * otherps], otherpoints[((i - 1) * otherps) + 1],
                        otherpoints[i * otherps], otherpoints[(i * otherps) + 1]
                    );

                    if (intersect !== null) {
                        return intersect;
                    }
                }

                console.error("intersectionPoint() should only be called when an intersection happens");
            }

            function bottomTraversal(start_i, end_i) {
                console.assert(start_i >= end_i, "the start should be the rightmost point, and the end should be the leftmost (excluding the equal or intersecting point)");

                var i;

                for (i = start_i; i >= end_i; i--) {
                    ctx.lineTo(
                        otherseries.xaxis.p2c(otherpoints[i * otherps]) + plotOffset.left,
                        otherseries.yaxis.p2c(otherpoints[(i * otherps) + 1]) + plotOffset.top
                    );
                }

                closePolygon();
            }

            function topTraversal(start_i, end_i) {
                console.assert(start_i <= end_i, "the start should be the rightmost point, and the end should be the leftmost (excluding the equal or intersecting point)");

                var i,
                    intersect;

                for (i = start_i; i < end_i; i++) {
                    if (points[(i * ps) + 1] === null && i > start_i) {
                        bottomTraversal(i - 1, start_i);
                        findNextStart(i, end_i);
                        return;
                    }

                    else if (points[(i * ps) + 1] === otherpoints[(i * otherps) + 1]) {
                        bottomTraversal(i, start_i);
                        findNextStart(i, end_i);
                        return;
                    }

                    else if (points[(i * ps) + 1] < otherpoints[(i * otherps) + 1]) {
                        intersect = intersectionPoint(i);
                        ctx.lineTo(
                            series.xaxis.p2c(intersect[0]) + plotOffset.left,
                            series.yaxis.p2c(intersect[1]) + plotOffset.top
                        );
                        bottomTraversal(i, start_i);
                        findNextStart(i, end_i);
                        return;

                    }

                    else {
                        ctx.lineTo(
                            series.xaxis.p2c(points[i * ps]) + plotOffset.left,
                            series.yaxis.p2c(points[(i * ps) + 1]) + plotOffset.top
                        );
                    }
                }

                bottomTraversal(end_i, start_i);
            }


            // Begin processing

            otherseries = findBelowSeries( series, plot.getData() );

            if ( !otherseries ) {
                return;
            }

            ps = series.datapoints.pointsize;
            points = series.datapoints.points;
            otherps = otherseries.datapoints.pointsize;
            otherpoints = otherseries.datapoints.points;
            plotOffset = plot.getPlotOffset();

            if (!validateInput()) {
                return;
            }


            // Flot's getFillStyle() should probably be exposed somewhere
            fillStyle = $.color.parse(series.color);
            fillStyle.a = 0.4;
            fillStyle.normalize();
            ctx.fillStyle = fillStyle.toString();


            // Begin recursive bi-directional traversal
            findNextStart(0, points.length/ps);
        }

        plot.hooks.drawSeries.push(plotDifferenceArea);
    }

    $.plot.plugins.push({
        init: init,
        options: options,
        name: "fillbelow",
        version: "0.1.0"
    });

})(jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.gauge.js":
/*!*************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.gauge.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/*!
 * jquery.flot.gauge v1.1.0 *
 *
 * Flot plugin for rendering gauge charts.
 *
 * Copyright (c) 2015 @toyoty99.
 * Licensed under the MIT license.
 */

/**
 * @module flot.gauge
 */
(function($) {


    /**
     * Gauge class
     *
     * @class Gauge
     */
    var Gauge = (function() {
        /**
         * context of canvas
         *
         * @property context
         * @type Object
         */
        var context;
        /**
         * placeholder of canvas
         *
         * @property placeholder
         * @type Object
         */
        var placeholder;
        /**
         * options of plot
         *
         * @property options
         * @type Object
         */
        var options;
        /**
         * options of gauge
         *
         * @property gaugeOptions
         * @type Object
         */
        var gaugeOptions;
        /**
         * data series
         *
         * @property series
         * @type Array
         */
        var series;
        /**
         * logger
         *
         * @property logger
         * @type Object
         */
        var logger;

        /**
         * constructor
         *
         * @class Gauge
         * @constructor
         * @param  {Object} gaugeOptions gauge options
         */
        var Gauge = function(plot, ctx) {
            context = ctx;
            placeholder = plot.getPlaceholder();
            options = plot.getOptions();
            gaugeOptions = options.series.gauges;
            series = plot.getData();
            logger = getLogger(gaugeOptions.debug);
        }

        /**
         * calculate layout
         *
         * @method calculateLayout
         * @return the calculated layout properties
         */
        Gauge.prototype.calculateLayout = function() {

            var canvasWidth = placeholder.width();
            var canvasHeight = placeholder.height();



            // calculate cell size
            var columns = Math.min(series.length, gaugeOptions.layout.columns);
            var rows = Math.ceil(series.length / columns);



            var margin = gaugeOptions.layout.margin;
            var hMargin = gaugeOptions.layout.hMargin;
            var vMargin = gaugeOptions.layout.vMargin;
            var cellWidth = (canvasWidth - (margin * 2) - (hMargin * (columns - 1))) / columns;
            var cellHeight = (canvasHeight - (margin * 2) - (vMargin * (rows - 1))) / rows;
            if (gaugeOptions.layout.square) {
                var cell = Math.min(cellWidth, cellHeight);
                cellWidth = cell;
                cellHeight = cell;
            }



            // calculate 'auto' values
            calculateAutoValues(gaugeOptions, cellWidth);

            // calculate maximum radius
            var cellMargin = gaugeOptions.cell.margin;
            var labelMargin = 0;
            var labelFontSize = 0;
            if (gaugeOptions.label.show) {
                labelMargin = gaugeOptions.label.margin;
                labelFontSize = gaugeOptions.label.font.size;
            }
            var valueMargin = 0;
            var valueFontSize = 0;
            if (gaugeOptions.value.show) {
                valueMargin = gaugeOptions.value.margin;
                valueFontSize = gaugeOptions.value.font.size;
            }
            var thresholdWidth = 0;
            if (gaugeOptions.threshold.show) {
                thresholdWidth = gaugeOptions.threshold.width;
            }
            var thresholdLabelMargin = 0;
            var thresholdLabelFontSize = 0;
            if (gaugeOptions.threshold.label.show) {
                thresholdLabelMargin = gaugeOptions.threshold.label.margin;
                thresholdLabelFontSize = gaugeOptions.threshold.label.font.size;
            }

            var maxRadiusH = (cellWidth / 2) - cellMargin - thresholdWidth - (thresholdLabelMargin * 2) - thresholdLabelFontSize;

            var startAngle = gaugeOptions.gauge.startAngle;
            var endAngle = gaugeOptions.gauge.endAngle;
            var dAngle = (endAngle - startAngle) / 100;
            var heightRatioV = -1;
            for (var a = startAngle; a < endAngle; a += dAngle) {
                heightRatioV = Math.max(heightRatioV, Math.sin(toRad(a)));
            }
            heightRatioV = Math.max(heightRatioV, Math.sin(toRad(endAngle)));
            var outerRadiusV = (cellHeight - (cellMargin * 2) - (labelMargin * 2) - labelFontSize) / (1 + heightRatioV);
            if (outerRadiusV * heightRatioV < valueMargin + (valueFontSize / 2)) {
                outerRadiusV = cellHeight - (cellMargin * 2) - (labelMargin * 2) - labelFontSize - valueMargin - (valueFontSize / 2);
            }
            var maxRadiusV = outerRadiusV - (thresholdLabelMargin * 2) - thresholdLabelFontSize - thresholdWidth;

            var radius = Math.min(maxRadiusH, maxRadiusV);


            var width = gaugeOptions.gauge.width;
            if (width >= radius) {
                width = Math.max(3, radius / 3);
            }


            var outerRadius = (thresholdLabelMargin * 2) + thresholdLabelFontSize + thresholdWidth + radius;
            var gaugeOuterHeight = Math.max(outerRadius * (1 + heightRatioV), outerRadius + valueMargin + (valueFontSize / 2));

            return {
                canvasWidth: canvasWidth,
                canvasHeight: canvasHeight,
                margin: margin,
                hMargin: hMargin,
                vMargin: vMargin,
                columns: columns,
                rows: rows,
                cellWidth: cellWidth,
                cellHeight: cellHeight,
                cellMargin: cellMargin,
                labelMargin: labelMargin,
                labelFontSize: labelFontSize,
                valueMargin: valueMargin,
                valueFontSize: valueFontSize,
                width: width,
                radius: radius,
                thresholdWidth: thresholdWidth,
                thresholdLabelMargin: thresholdLabelMargin,
                thresholdLabelFontSize: thresholdLabelFontSize,
                gaugeOuterHeight: gaugeOuterHeight
            };
        }

        /**
         * calculate the values which are set as 'auto'
         *
         * @method calculateAutoValues
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Number} cellWidth the width of cell
         */
        function calculateAutoValues(gaugeOptionsi, cellWidth) {

            if (gaugeOptionsi.gauge.width === "auto") {
                gaugeOptionsi.gauge.width = Math.max(5, cellWidth / 8);
            }
            if (gaugeOptionsi.label.margin === "auto") {
                gaugeOptionsi.label.margin = Math.max(1, cellWidth / 20);
            }
            if (gaugeOptionsi.label.font.size === "auto") {
                gaugeOptionsi.label.font.size = Math.max(5, cellWidth / 8);
            }
            if (gaugeOptionsi.value.margin === "auto") {
                gaugeOptionsi.value.margin = Math.max(1, cellWidth / 30);
            }
            if (gaugeOptionsi.value.font.size === "auto") {
                gaugeOptionsi.value.font.size = Math.max(5, cellWidth / 9);
            }
            if (gaugeOptionsi.threshold.width === "auto") {
                gaugeOptionsi.threshold.width = Math.max(3, cellWidth / 100);
            }
            if (gaugeOptionsi.threshold.label.margin === "auto") {
                gaugeOptionsi.threshold.label.margin = Math.max(3, cellWidth / 40);
            }
            if (gaugeOptionsi.threshold.label.font.size === "auto") {
                gaugeOptionsi.threshold.label.font.size = Math.max(5, cellWidth / 15);
            }

        }
        Gauge.prototype.calculateAutoValues = calculateAutoValues;

        /**
         * calculate the layout of the cell inside
         *
         * @method calculateCellLayout
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Number} cellWidth the width of cell
         * @param  {Number} i the index of the series
         * @return the calculated cell layout properties
         */
        Gauge.prototype.calculateCellLayout = function(gaugeOptionsi, layout, i) {

            // calculate top, left and center
            var c = col(layout.columns, i);
            var r = row(layout.columns, i);
            var x = layout.margin + (layout.cellWidth + layout.hMargin) * c;
            var y = layout.margin + (layout.cellHeight + layout.vMargin) * r;
            var cx = x + (layout.cellWidth / 2);
            var cy = y + layout.cellMargin + (layout.labelMargin * 2) + layout.labelFontSize + layout.thresholdWidth
                        + layout.thresholdLabelFontSize + (layout.thresholdLabelMargin * 2) + layout.radius;
            var blank = layout.cellHeight - (layout.cellMargin * 2) - (layout.labelMargin * 2) - layout.labelFontSize - layout.gaugeOuterHeight;
            var offsetY = 0;
            if (gaugeOptionsi.cell.vAlign === "middle") {
                offsetY = (blank / 2);
            } else if (gaugeOptionsi.cell.vAlign === "bottom") {
                offsetY = blank;
            }
            cy += offsetY;

            return {
                col: c,
                row: r,
                x: x,
                y: y,
                offsetY: offsetY,
                cellWidth: layout.cellWidth,
                cellHeight: layout.cellHeight,
                cellMargin: layout.cellMargin,
                cx: cx,
                cy: cy
            }
        }

        /**
         * draw the background of chart
         *
         * @method drawBackground
         * @param  {Object} layout the layout properties
         */
        Gauge.prototype.drawBackground = function(layout) {

            if (!gaugeOptions.frame.show) {
                return;
            }
            context.save();
            context.strokeStyle = options.grid.borderColor;
            context.lineWidth = options.grid.borderWidth;
            context.strokeRect(0, 0, layout.canvasWidth, layout.canvasHeight);
            if (options.grid.backgroundColor) {
                context.fillStyle = options.grid.backgroundColor;
                context.fillRect(0, 0, layout.canvasWidth, layout.canvasHeight);
            }
            context.restore();
        }

        /**
         * draw the background of cell
         *
         * @method drawCellBackground
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} cellLayout the cell layout properties
         */
        Gauge.prototype.drawCellBackground = function(gaugeOptionsi, cellLayout) {

            context.save();
            if (gaugeOptionsi.cell.border && gaugeOptionsi.cell.border.show && gaugeOptionsi.cell.border.color && gaugeOptionsi.cell.border.width) {
                context.strokeStyle = gaugeOptionsi.cell.border.color;
                context.lineWidth = gaugeOptionsi.cell.border.width;
                context.strokeRect(cellLayout.x, cellLayout.y, cellLayout.cellWidth, cellLayout.cellHeight);
            }
            if (gaugeOptionsi.cell.background && gaugeOptionsi.cell.background.color) {
                context.fillStyle = gaugeOptionsi.cell.background.color;
                context.fillRect(cellLayout.x, cellLayout.y, cellLayout.cellWidth, cellLayout.cellHeight);
            }
            context.restore();
        }

        /**
         * draw the gauge
         *
         * @method drawGauge
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Object} cellLayout the cell layout properties
         * @param  {String} label the label of data
         * @param  {Number} data the value of the gauge
         */
        Gauge.prototype.drawGauge = function(gaugeOptionsi, layout, cellLayout, label, data) {


            var blur = gaugeOptionsi.gauge.shadow.show ? gaugeOptionsi.gauge.shadow.blur : 0;


            // draw gauge frame
            drawArcWithShadow(
                cellLayout.cx, // center x
                cellLayout.cy, // center y
                layout.radius,
                layout.width,
                toRad(gaugeOptionsi.gauge.startAngle),
                toRad(gaugeOptionsi.gauge.endAngle),
                gaugeOptionsi.gauge.border.color,      // line color
                gaugeOptionsi.gauge.border.width,      // line width
                gaugeOptionsi.gauge.background.color,  // fill color
                blur);

            // draw gauge
            var c1 = getColor(gaugeOptionsi, data);
            var a2 = calculateAngle(gaugeOptionsi, layout, data);
            drawArcWithShadow(
                cellLayout.cx, // center x
                cellLayout.cy, // center y
                layout.radius - 1,
                layout.width - 2,
                toRad(gaugeOptionsi.gauge.startAngle),
                toRad(a2),
                c1,           // line color
                1,            // line width
                c1,           // fill color
                blur);
        }

        /**
         * decide the color of the data from the threshold options
         *
         * @method getColor
         * @private
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Number} data the value of the gauge
         */
        function getColor(gaugeOptionsi, data) {
            var color;
            for (var i = 0; i < gaugeOptionsi.threshold.values.length; i++) {
                var threshold = gaugeOptionsi.threshold.values[i];
                color = threshold.color;
                if (data < threshold.value) {
                    break;
                }
            }
            return color;
        }

        /**
         * calculate the angle of the data
         *
         * @method calculateAngle
         * @private
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Number} data the value of the gauge
         */
        function calculateAngle(gaugeOptionsi, layout, data) {
            var a =
                gaugeOptionsi.gauge.startAngle
                    + (gaugeOptionsi.gauge.endAngle - gaugeOptionsi.gauge.startAngle)
                        * ((data - gaugeOptionsi.gauge.min) / (gaugeOptionsi.gauge.max - gaugeOptionsi.gauge.min));

            if (a < gaugeOptionsi.gauge.startAngle) {
                a = gaugeOptionsi.gauge.startAngle;
            } else if (a > gaugeOptionsi.gauge.endAngle) {
                a = gaugeOptionsi.gauge.endAngle;
            }
            return a;
        }

        /**
         * draw the arc of the threshold
         *
         * @method drawThreshold
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Object} cellLayout the cell layout properties
         */
        Gauge.prototype.drawThreshold = function(gaugeOptionsi, layout, cellLayout) {

            var a1 = gaugeOptionsi.gauge.startAngle;
            for (var i = 0; i < gaugeOptionsi.threshold.values.length; i++) {
                var threshold = gaugeOptionsi.threshold.values[i];
                c1 = threshold.color;
                a2 = calculateAngle(gaugeOptionsi, layout, threshold.value);
                drawArc(
                    context,
                    cellLayout.cx, // center x
                    cellLayout.cy, // center y
                    layout.radius + layout.thresholdWidth,
                    layout.thresholdWidth - 2,
                    toRad(a1),
                    toRad(a2),
                    c1,           // line color
                    1,            // line width
                    c1);          // fill color
                a1 = a2;
            }
        }

        /**
         * draw an arc with a shadow
         *
         * @method drawArcWithShadow
         * @private
         * @param  {Number} cx the x position of the center
         * @param  {Number} cy the y position of the center
         * @param  {Number} r the radius of an arc
         * @param  {Number} w the width of an arc
         * @param  {Number} rd1 the start angle of an arc in radians
         * @param  {Number} rd2 the end angle of an arc in radians
         * @param  {String} lc the color of a line
         * @param  {Number} lw the widht of a line
         * @param  {String} fc the fill color  of an arc
         * @param  {Number} blur the shdow blur
         */
        function drawArcWithShadow(cx, cy, r, w, rd1, rd2, lc, lw, fc, blur) {
            if (rd1 === rd2) {
                return;
            }
            context.save();

            drawArc(context, cx, cy, r, w, rd1, rd2, lc, lw, fc);

            if (blur) {
                drawArc(context, cx, cy, r, w, rd1, rd2);
                context.clip();
                context.shadowOffsetX = 0;
                context.shadowOffsetY = 0;
                context.shadowBlur = 10;
                context.shadowColor = "gray";
                drawArc(context, cx, cy, r + 1, w + 2, rd1, rd2, lc, 1);
            }
            context.restore();
        }

        /**
         * draw the label of the gauge
         *
         * @method drawLable
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Object} cellLayout the cell layout properties
         * @param  {Number} i the index of the series
         * @param  {Object} item the item of the series
         */
        Gauge.prototype.drawLable = function(gaugeOptionsi, layout, cellLayout, i, item) {

            drawText(
                cellLayout.cx,
                cellLayout.y + cellLayout.cellMargin + layout.labelMargin + cellLayout.offsetY,
                "flotGagueLabel" + i,
                gaugeOptionsi.label.formatter ? gaugeOptionsi.label.formatter(item.label, item.data[0][1]) : text,
                gaugeOptionsi.label);
        }

        /**
         * draw the value of the gauge
         *
         * @method drawValue
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Object} cellLayout the cell layout properties
         * @param  {Number} i the index of the series
         * @param  {Object} item the item of the series
         */
        Gauge.prototype.drawValue = function(gaugeOptionsi, layout, cellLayout, i, item) {

            drawText(
                cellLayout.cx,
                cellLayout.cy - (gaugeOptionsi.value.font.size / 2),
                "flotGagueValue" + i,
                gaugeOptionsi.value.formatter ? gaugeOptionsi.value.formatter(item.label, item.data[0][1]) : text,
                gaugeOptionsi.value);
        }

        /**
         * draw the values of the threshold
         *
         * @method drawThresholdValues
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Object} cellLayout the cell layout properties
         * @param  {Number} i the index of the series
         */
        Gauge.prototype.drawThresholdValues = function(gaugeOptionsi, layout, cellLayout, i) {

            // min, max
            drawThresholdValue(gaugeOptionsi, layout, cellLayout, "Min" + i, gaugeOptionsi.gauge.min, gaugeOptionsi.gauge.startAngle);
            drawThresholdValue(gaugeOptionsi, layout, cellLayout, "Max" + i, gaugeOptionsi.gauge.max, gaugeOptionsi.gauge.endAngle);
            // threshold values
            for (var j = 0; j < gaugeOptionsi.threshold.values.length; j++) {
                var threshold = gaugeOptionsi.threshold.values[j];
                if (threshold.value > gaugeOptionsi.gauge.min && threshold.value < gaugeOptionsi.gauge.max) {
                    var a = calculateAngle(gaugeOptionsi, layout, threshold.value);
                    drawThresholdValue(gaugeOptionsi, layout, cellLayout, i + "_" + j, threshold.value, a);
                }
            }
        }

        /**
         * draw the value of the threshold
         *
         * @method drawThresholdValue
         * @param  {Object} gaugeOptionsi the options of the gauge
         * @param  {Object} layout the layout properties
         * @param  {Object} cellLayout the cell layout properties
         * @param  {Number} i the index of the series
         * @param  {Number} value the value of the threshold
         * @param  {Number} a the angle of the value drawn
         */
        function drawThresholdValue(gaugeOptionsi, layout, cellLayout, i, value, a) {
            drawText(
                cellLayout.cx
                    + ((layout.thresholdLabelMargin + (layout.thresholdLabelFontSize / 2) + layout.radius)
                        * Math.cos(toRad(a))),
                cellLayout.cy
                    + ((layout.thresholdLabelMargin + (layout.thresholdLabelFontSize / 2) + layout.radius)
                        * Math.sin(toRad(a))),
                "flotGagueThresholdValue" + i,
                gaugeOptionsi.threshold.label.formatter ? gaugeOptionsi.threshold.label.formatter(value) : value,
                gaugeOptionsi.threshold.label,
                a);
        }

        /**
         * draw a text
         *
         * the textOptions is assumed as follows:
         *
         *   textOptions: {
         *       background: {
         *           color: null,
         *           opacity: 0
         *       },
         *       font: {
         *           size: "auto"
         *           family: "\"ＭＳ ゴシック\",sans-serif"
         *       },
         *       color: null
         *   }
         *
         * @method drawText
         * @private
         * @param  {Number} x the x position of the text drawn (left top)
         * @param  {Number} y the y position of the text drawn (left top)
         * @param  {String} id the id of the dom element
         * @param  {String} text the text drawn
         * @param  {Object} textOptions the option of the text
         * @param  {Number} [a] the angle of the value drawn
         */
        function drawText(x, y, id, text, textOptions, a) {
            var span = $(placeholder).find("#" + id);
            var exists = span.length;
            if (!exists) {
                span = $("<span></span>")
                span.attr("id", id);
                span.attr("class", "flot-temp-elem");
                placeholder.append(span);
            }

            span.css("position", "absolute");
            span.css("top", y + "px");
            span.css("white-space", "nowrap");

            if (textOptions.font.size) {
              span.css("font-size", textOptions.font.size + "px");
            }
            if (textOptions.font.family) {
              span.css("font-family", textOptions.font.family);
            }
            if (textOptions.color) {
              span.css("color", textOptions.color);
            }
            if (textOptions.background.color) {
              span.css("background-color", textOptions.background.color);
            }
            if (textOptions.background.opacity) {
              span.css("opacity", textOptions.background.opacity);
            }
            span.text(text);
            // after append, readjust the left position
            span.css("left", x + "px"); // for redraw, resetting the left position is needed here
            span.css("left", (parseInt(span.css("left")) - (span.width()/ 2)) + "px");

            // at last, set angle
            if (!exists && a) {
                span.css("top", (parseInt(span.css("top")) - (span.height()/ 2)) + "px");
                span.css("transform", "rotate(" + ((180 * a) + 90) + "deg)"); // not supported for ie8
            }
        }

        return Gauge;
    })();
    /**
     * get a instance of Logger
     *
     * @method  getLogger
     * @for flot.gauge
     * @private
     * @param  {Object} debugOptions the options of debug
     */
    function getLogger(debugOptions) {
        return typeof Logger !== "undefined" ? new Logger(debugOptions) : null;
    }

    /**
     * calculate the index of columns for the specified data
     *
     * @method col
     * @for flot.gauge
     * @param  {Number} columns the number of columns
     * @param  {Number} i       the index of the series
     * @return the index of columns
     */
    function col(columns, i) {
        return i % columns;
    }

    /**
     * calculate the index of rows for the specified data
     *
     * @method row
     * @for flot.gauge
     * @param  {Number} columns the number of rows
     * @param  {Number} i       the index of the series
     * @return the index of rows
     */
    function row(columns, i) {
        return Math.floor(i / columns);
    }

    /**
     * calculate the angle in radians
     *
     * internally, use a number without PI (0 - 2).
     * so, in this function, multiply PI
     *
     * @method toRad
     * @for flot.gauge
     * @param  {Number} a the number of angle without PI
     * @return the angle in radians
     */
    function toRad(a) {
        return a * Math.PI;
    }

    /**
     * draw an arc
     *
     * @method drawArc
     * @for flot.gauge
     * @param  {Object} context the context of canvas
     * @param  {Number} cx the x position of the center
     * @param  {Number} cy the y position of the center
     * @param  {Number} r the radius of an arc
     * @param  {Number} w the width of an arc
     * @param  {Number} rd1 the start angle of an arc in radians
     * @param  {Number} rd2 the end angle of an arc in radians
     * @param  {String} lc the color of a line
     * @param  {Number} lw the widht of a line
     * @param  {String} fc the fill color  of an arc
     */
    function drawArc(context, cx, cy, r, w, rd1, rd2, lc, lw, fc) {
        if (rd1 === rd2) {
            return;
        }
        var counterClockwise = false;
        context.save();
        context.beginPath();
        context.arc(cx, cy, r, rd1, rd2, counterClockwise);
        context.lineTo(cx + (r - w) * Math.cos(rd2),
                       cy + (r - w) * Math.sin(rd2));
        context.arc(cx, cy, r - w, rd2, rd1, !counterClockwise);
        context.closePath();
        if (lw) {
            context.lineWidth = lw;
        }
        if (lc) {
            context.strokeStyle = lc;
            context.stroke();
        }
        if (fc) {
            context.fillStyle = fc;
            context.fill();
        }
        context.restore();
    }

    /**
     * initialize plugin
     *
     * @method init
     * @for flot.gauge
     * @private
     * @param  {Object} plot a instance of plot
     */
    function init (plot) {
        // add processOptions hook
        plot.hooks.processOptions.push(function(plot, options) {
            var logger = getLogger(options.series.gauges.debug);




            // turn 'grid' and 'legend' off
            if (options.series.gauges.show) {
                options.grid.show = false;
                options.legend.show = false;
            }

            // sort threshold
            var thresholds = options.series.gauges.threshold.values;

            thresholds.sort(function(a, b) {
                if (a.value < b.value) {
                    return -1;
                } else if (a.value > b.value) {
                    return 1;
                } else {
                    return 0;
                }
            });



        });

        // add draw hook
        plot.hooks.draw.push(function(plot, context) {
            var options = plot.getOptions();
            var gaugeOptions = options.series.gauges;

            var logger = getLogger(gaugeOptions.debug);


            if (!gaugeOptions.show) {
                return;
            }

            var series = plot.getData();

            if (!series || !series.length) {
                return; // if no series were passed
            }

            var gauge = new Gauge(plot, context);

            // calculate layout
            var layout = gauge.calculateLayout();

            // debug layout
            if (gaugeOptions.debug.layout) {

            }

            // draw background
            gauge.drawBackground(layout)

            // draw cells (label, gauge, value, threshold)
            for (var i = 0; i < series.length; i++) {
                var item = series[i];

                var gaugeOptionsi = $.extend({}, gaugeOptions, item.gauges);
                if (item.gauges) {
                    // re-calculate 'auto' values
                    gauge.calculateAutoValues(gaugeOptionsi, layout.cellWidth);
                }

                // calculate cell layout
                var cellLayout = gauge.calculateCellLayout(gaugeOptionsi, layout, i);

                // draw cell background
                gauge.drawCellBackground(gaugeOptionsi, cellLayout)
                // debug layout
                if (gaugeOptionsi.debug.layout) {

                }
                // draw label
                if (gaugeOptionsi.label.show) {
                    gauge.drawLable(gaugeOptionsi, layout, cellLayout, i, item);
                }
                // draw gauge
                gauge.drawGauge(gaugeOptionsi, layout, cellLayout, item.label, item.data[0][1]);
                // draw threshold
                if (gaugeOptionsi.threshold.show) {
                    gauge.drawThreshold(gaugeOptionsi, layout, cellLayout);
                }
                if (gaugeOptionsi.threshold.label.show) {
                    gauge.drawThresholdValues(gaugeOptionsi, layout, cellLayout, i)
                }
                // draw value
                if (gaugeOptionsi.value.show) {
                    gauge.drawValue(gaugeOptionsi, layout, cellLayout, i, item);
                }
            }
        });
    }

    /**
     * [defaults description]
     *
     * @property defaults
     * @type {Object}
     */
    var defaults = {
        series: {
            gauges: {
                debug: {
                    log: false,
                    layout: false,
                    alert: false
                },
                show: false,
                layout: {
                    margin: 5,
                    columns: 3,
                    hMargin: 5,
                    vMargin: 5,
                    square: false
                },
                frame: {
                    show: true
                },
                cell: {
                    background: {
                        color: null
                    },
                    border: {
                        show: true,
                        color: "black",
                        width: 1
                    },
                    margin: 5,
                    vAlign: "middle" // 'top' or 'middle' or 'bottom'
                },
                gauge: {
                    width: "auto", // a specified number, or 'auto'
                    startAngle: 0.9, // 0 - 2 factor of the radians
                    endAngle: 2.1, // 0 - 2 factor of the radians
                    min: 0,
                    max: 100,
                    background: {
                        color: "white"
                    },
                    border: {
                        color: "lightgray",
                        width: 2
                    },
                    shadow: {
                        show: true,
                        blur: 5
                    }
                },
                label: {
                    show: true,
                    margin: "auto", // a specified number, or 'auto'
                    background: {
                        color: null,
                        opacity: 0
                    },
                    font: {
                        size: "auto", // a specified number, or 'auto'
                        family: "sans-serif"
                    },
                    color: null,
                    formatter: function(label, value) {
                        return label;
                    }
                },
                value: {
                    show: true,
                    margin: "auto", // a specified number, or 'auto'
                    background: {
                        color: null,
                        opacity: 0
                    },
                    font: {
                        size: "auto", // a specified number, or 'auto'
                        family: "sans-serif"
                    },
                    color: null,
                    formatter: function(label, value) {
                        return parseInt(value);
                    }
                },
                threshold: {
                    show: true,
                    width: "auto", // a specified number, or 'auto'
                    label: {
                        show: true,
                        margin: "auto", // a specified number, or 'auto'
                        background: {
                            color: null,
                            opacity: 0
                        },
                        font: {
                            size: "auto", // a specified number, or 'auto'
                            family: ",sans-serif"
                        },
                        color: null,
                        formatter: function(value) {
                            return value;
                        }
                    },
                    values: [

                    ]
                }
            }
        }
    };

    // register the gauge plugin
    $.plot.plugins.push({
        init: init,
        options: defaults,
        name: "gauge",
        version: "1.1.0"
    });

})(jQuery);



/***/ }),

/***/ "./public/vendor/flot/jquery.flot.js":
/*!*******************************************!*\
  !*** ./public/vendor/flot/jquery.flot.js ***!
  \*******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* Javascript plotting library for jQuery, version 0.8.3.

Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.

*/

// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience

/* Plugin for jQuery for working with colors.
 *
 * Version 1.1.
 *
 * Inspiration from jQuery color animation plugin by John Resig.
 *
 * Released under the MIT license by Ole Laursen, October 2009.
 *
 * Examples:
 *
 *   $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
 *   var c = $.color.extract($("#mydiv"), 'background-color');
 *   console.log(c.r, c.g, c.b, c.a);
 *   $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
 *
 * Note that .scale() and .add() return the same modified object
 * instead of making a new one.
 *
 * V. 1.1: Fix error handling so e.g. parsing an empty string does
 * produce a color rather than just crashing.
 */
(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);

// the actual Flot code
(function($) {

	// Cache the prototype hasOwnProperty for faster access

	var hasOwnProperty = Object.prototype.hasOwnProperty;

    // A shim to provide 'detach' to jQuery versions prior to 1.4.  Using a DOM
    // operation produces the same effect as detach, i.e. removing the element
    // without touching its jQuery data.

    // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.

    if (!$.fn.detach) {
        $.fn.detach = function() {
            return this.each(function() {
                if (this.parentNode) {
                    this.parentNode.removeChild( this );
                }
            });
        };
    }

	///////////////////////////////////////////////////////////////////////////
	// The Canvas object is a wrapper around an HTML5 <canvas> tag.
	//
	// @constructor
	// @param {string} cls List of classes to apply to the canvas.
	// @param {element} container Element onto which to append the canvas.
	//
	// Requiring a container is a little iffy, but unfortunately canvas
	// operations don't work unless the canvas is attached to the DOM.

	function Canvas(cls, container) {

		var element = container.children("." + cls)[0];

		if (element == null) {

			element = document.createElement("canvas");
			element.className = cls;

			$(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
				.appendTo(container);

			// If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas

			if (!element.getContext) {
				if (window.G_vmlCanvasManager) {
					element = window.G_vmlCanvasManager.initElement(element);
				} else {
					throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
				}
			}
		}

		this.element = element;

		var context = this.context = element.getContext("2d");

		// Determine the screen's ratio of physical to device-independent
		// pixels.  This is the ratio between the canvas width that the browser
		// advertises and the number of pixels actually present in that space.

		// The iPhone 4, for example, has a device-independent width of 320px,
		// but its screen is actually 640px wide.  It therefore has a pixel
		// ratio of 2, while most normal devices have a ratio of 1.

		var devicePixelRatio = window.devicePixelRatio || 1,
			backingStoreRatio =
				context.webkitBackingStorePixelRatio ||
				context.mozBackingStorePixelRatio ||
				context.msBackingStorePixelRatio ||
				context.oBackingStorePixelRatio ||
				context.backingStorePixelRatio || 1;

		this.pixelRatio = devicePixelRatio / backingStoreRatio;

		// Size the canvas to match the internal dimensions of its container

		this.resize(container.width(), container.height());

		// Collection of HTML div layers for text overlaid onto the canvas

		this.textContainer = null;
		this.text = {};

		// Cache of text fragments and metrics, so we can avoid expensively
		// re-calculating them when the plot is re-rendered in a loop.

		this._textCache = {};
		this._textSizeCache = window.flotTextSizeCache = window.flotTextSizeCache || {};
	}

	// Resizes the canvas to the given dimensions.
	//
	// @param {number} width New width of the canvas, in pixels.
	// @param {number} width New height of the canvas, in pixels.

	Canvas.prototype.resize = function(width, height) {

		if (width <= 0 || height <= 0) {
			throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
		}

		var element = this.element,
			context = this.context,
			pixelRatio = this.pixelRatio;

		// Resize the canvas, increasing its density based on the display's
		// pixel ratio; basically giving it more pixels without increasing the
		// size of its element, to take advantage of the fact that retina
		// displays have that many more pixels in the same advertised space.

		// Resizing should reset the state (excanvas seems to be buggy though)

		if (this.width != width) {
			element.width = width * pixelRatio;
			element.style.width = width + "px";
			this.width = width;
		}

		if (this.height != height) {
			element.height = height * pixelRatio;
			element.style.height = height + "px";
			this.height = height;
		}

		// Save the context, so we can reset in case we get replotted.  The
		// restore ensure that we're really back at the initial state, and
		// should be safe even if we haven't saved the initial state yet.

		context.restore();
		context.save();

		// Scale the coordinate space to match the display density; so even though we
		// may have twice as many pixels, we still want lines and other drawing to
		// appear at the same size; the extra pixels will just make them crisper.

		context.scale(pixelRatio, pixelRatio);
	};

	// Clears the entire canvas area, not including any overlaid HTML text

	Canvas.prototype.clear = function() {
		this.context.clearRect(0, 0, this.width, this.height);
	};

	// Finishes rendering the canvas, including managing the text overlay.

	Canvas.prototype.render = function() {

		var cache = this._textCache;

		// For each text layer, add elements marked as active that haven't
		// already been rendered, and remove those that are no longer active.

		for (var layerKey in cache) {
			if (hasOwnProperty.call(cache, layerKey)) {

				var layer = this.getTextLayer(layerKey),
					layerCache = cache[layerKey];

				layer.hide();

				for (var styleKey in layerCache) {
					if (hasOwnProperty.call(layerCache, styleKey)) {
						var styleCache = layerCache[styleKey];
						for (var key in styleCache) {
							if (hasOwnProperty.call(styleCache, key)) {

								var positions = styleCache[key].positions;

								for (var i = 0, position; position = positions[i]; i++) {
									if (position.active) {
										if (!position.rendered) {
											layer.append(position.element);
											position.rendered = true;
										}
									} else {
										positions.splice(i--, 1);
										if (position.rendered) {
											position.element.detach();
										}
									}
								}

								if (positions.length == 0) {
									delete styleCache[key];
								}
							}
						}
					}
				}

				layer.show();
			}
		}
	};

	// Creates (if necessary) and returns the text overlay container.
	//
	// @param {string} classes String of space-separated CSS classes used to
	//     uniquely identify the text layer.
	// @return {object} The jQuery-wrapped text-layer div.

	Canvas.prototype.getTextLayer = function(classes) {

		var layer = this.text[classes];

		// Create the text layer if it doesn't exist

		if (layer == null) {

			// Create the text layer container, if it doesn't exist

			if (this.textContainer == null) {
				this.textContainer = $("<div class='flot-text flot-temp-elem'></div>")
					.css({
						position: "absolute",
						top: 0,
						left: 0,
						bottom: 0,
						right: 0,
						'font-size': "smaller",
						color: "#545454"
					})
					.insertAfter(this.element);
			}

			layer = this.text[classes] = $("<div></div>")
				.addClass(classes)
				.css({
					position: "absolute",
					top: 0,
					left: 0,
					bottom: 0,
					right: 0
				})
				.appendTo(this.textContainer);
		}

		return layer;
	};

	// Creates (if necessary) and returns a text info object.
	//
	// The object looks like this:
	//
	// {
	//     width: Width of the text's wrapper div.
	//     height: Height of the text's wrapper div.
	//     element: The jQuery-wrapped HTML div containing the text.
	//     positions: Array of positions at which this text is drawn.
	// }
	//
	// The positions array contains objects that look like this:
	//
	// {
	//     active: Flag indicating whether the text should be visible.
	//     rendered: Flag indicating whether the text is currently visible.
	//     element: The jQuery-wrapped HTML div containing the text.
	//     x: X coordinate at which to draw the text.
	//     y: Y coordinate at which to draw the text.
	// }
	//
	// Each position after the first receives a clone of the original element.
	//
	// The idea is that that the width, height, and general 'identity' of the
	// text is constant no matter where it is placed; the placements are a
	// secondary property.
	//
	// Canvas maintains a cache of recently-used text info objects; getTextInfo
	// either returns the cached element or creates a new entry.
	//
	// @param {string} layer A string of space-separated CSS classes uniquely
	//     identifying the layer containing this text.
	// @param {string} text Text string to retrieve info for.
	// @param {(string|object)=} font Either a string of space-separated CSS
	//     classes or a font-spec object, defining the text's font and style.
	// @param {number=} angle Angle at which to rotate the text, in degrees.
	//     Angle is currently unused, it will be implemented in the future.
	// @param {number=} width Maximum width of the text before it wraps.
	// @return {object} a text info object.

	Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {

		var textStyle, layerCache, styleCache, info;

		// Cast the value to a string, in case we were given a number or such

		text = "" + text;

		// If the font is a font-spec object, generate a CSS font definition

		if (typeof font === "object") {
			textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
		} else {
			textStyle = font;
		}

		// Retrieve (or create) the cache for the text's layer and styles

		layerCache = this._textCache[layer];

		if (layerCache == null) {
			layerCache = this._textCache[layer] = {};
		}

		styleCache = layerCache[textStyle];

		if (styleCache == null) {
			styleCache = layerCache[textStyle] = {};
		}

		info = styleCache[text];

		// If we can't find a matching element in our cache, create a new one

		if (info == null) {

			var element = $("<div></div>").html(text)
				.css({
					position: "absolute",
					'max-width': width,
					top: -9999
				})
				.appendTo(this.getTextLayer(layer));

			if (typeof font === "object") {
				element.css({
					font: textStyle,
					color: font.color
				});
			} else if (typeof font === "string") {
				element.addClass(font);
			}

      info = styleCache[text] = { element: element, positions: [] };

      var size = this._textSizeCache[text];
			if (size) {
        info.width = size.width;
        info.height = size.height;
			} else {
        info.width = element.outerWidth(true);
        info.height = element.outerHeight(true);
        this._textSizeCache[text] = { width: info.width, height: info.height };
			}
			element.detach();
		}

		return info;
	};

	// Adds a text string to the canvas text overlay.
	//
	// The text isn't drawn immediately; it is marked as rendering, which will
	// result in its addition to the canvas on the next render pass.
	//
	// @param {string} layer A string of space-separated CSS classes uniquely
	//     identifying the layer containing this text.
	// @param {number} x X coordinate at which to draw the text.
	// @param {number} y Y coordinate at which to draw the text.
	// @param {string} text Text string to draw.
	// @param {(string|object)=} font Either a string of space-separated CSS
	//     classes or a font-spec object, defining the text's font and style.
	// @param {number=} angle Angle at which to rotate the text, in degrees.
	//     Angle is currently unused, it will be implemented in the future.
	// @param {number=} width Maximum width of the text before it wraps.
	// @param {string=} halign Horizontal alignment of the text; either "left",
	//     "center" or "right".
	// @param {string=} valign Vertical alignment of the text; either "top",
	//     "middle" or "bottom".

	Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {

		var info = this.getTextInfo(layer, text, font, angle, width),
			positions = info.positions;

		// Tweak the div's position to match the text's alignment

		if (halign == "center") {
			x -= info.width / 2;
		} else if (halign == "right") {
			x -= info.width;
		}

		if (valign == "middle") {
			y -= info.height / 2;
		} else if (valign == "bottom") {
			y -= info.height;
		}

		// Determine whether this text already exists at this position.
		// If so, mark it for inclusion in the next render pass.

		for (var i = 0, position; position = positions[i]; i++) {
			if (position.x == x && position.y == y) {
				position.active = true;
				return;
			}
		}

		// If the text doesn't exist at this position, create a new entry

		// For the very first position we'll re-use the original element,
		// while for subsequent ones we'll clone it.

		position = {
			active: true,
			rendered: false,
			element: positions.length ? info.element.clone() : info.element,
			x: x,
			y: y
		};

		positions.push(position);

		// Move the element to its final position within the container

		position.element.css({
			top: Math.round(y),
			left: Math.round(x),
			'text-align': halign	// In case the text wraps
		});
	};

	// Removes one or more text strings from the canvas text overlay.
	//
	// If no parameters are given, all text within the layer is removed.
	//
	// Note that the text is not immediately removed; it is simply marked as
	// inactive, which will result in its removal on the next render pass.
	// This avoids the performance penalty for 'clear and redraw' behavior,
	// where we potentially get rid of all text on a layer, but will likely
	// add back most or all of it later, as when redrawing axes, for example.
	//
	// @param {string} layer A string of space-separated CSS classes uniquely
	//     identifying the layer containing this text.
	// @param {number=} x X coordinate of the text.
	// @param {number=} y Y coordinate of the text.
	// @param {string=} text Text string to remove.
	// @param {(string|object)=} font Either a string of space-separated CSS
	//     classes or a font-spec object, defining the text's font and style.
	// @param {number=} angle Angle at which the text is rotated, in degrees.
	//     Angle is currently unused, it will be implemented in the future.

	Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
		if (text == null) {
			var layerCache = this._textCache[layer];
			if (layerCache != null) {
				for (var styleKey in layerCache) {
					if (hasOwnProperty.call(layerCache, styleKey)) {
						var styleCache = layerCache[styleKey];
						for (var key in styleCache) {
							if (hasOwnProperty.call(styleCache, key)) {
								var positions = styleCache[key].positions;
								for (var i = 0, position; position = positions[i]; i++) {
									position.active = false;
								}
							}
						}
					}
				}
			}
		} else {
			var positions = this.getTextInfo(layer, text, font, angle).positions;
			for (var i = 0, position; position = positions[i]; i++) {
				if (position.x == x && position.y == y) {
					position.active = false;
				}
			}
		}
	};

	///////////////////////////////////////////////////////////////////////////
	// The top-level container for the entire plot.

    function Plot(placeholder, data_, options_, plugins) {
        // data is on the form:
        //   [ series1, series2 ... ]
        // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
        // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }

        var series = [],
            options = {
                // the color theme used for graphs
                colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
                legend: {
                    show: true,
                    noColumns: 1, // number of colums in legend table
                    labelFormatter: null, // fn: string -> string
                    labelBoxBorderColor: "#ccc", // border color for the little label boxes
                    container: null, // container (as jQuery object) to put legend in, null means default on top of graph
                    position: "ne", // position of default legend container within plot
                    margin: 5, // distance from grid edge to default legend container within plot
                    backgroundColor: null, // null means auto-detect
                    backgroundOpacity: 0.85, // set to 0 to avoid background
                    sorted: null    // default to no legend sorting
                },
                xaxis: {
                    show: null, // null = auto-detect, true = always, false = never
                    position: "bottom", // or "top"
                    mode: null, // null or "time"
                    font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
                    color: null, // base color, labels, ticks
                    tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
                    transform: null, // null or f: number -> number to transform axis
                    inverseTransform: null, // if transform is set, this should be the inverse function
                    min: null, // min. value to show, null means set automatically
                    max: null, // max. value to show, null means set automatically
                    autoscaleMargin: null, // margin in % to add if auto-setting min/max
                    ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
                    tickFormatter: null, // fn: number -> string
                    labelWidth: null, // size of tick labels in pixels
                    labelHeight: null,
                    reserveSpace: null, // whether to reserve space even if axis isn't shown
                    tickLength: null, // size in pixels of ticks, or "full" for whole line
                    alignTicksWithAxis: null, // axis number or null for no sync
                    tickDecimals: null, // no. of decimals, null means auto
                    tickSize: null, // number or [number, "unit"]
                    minTickSize: null // number or [number, "unit"]
                },
                yaxis: {
                    autoscaleMargin: 0.02,
                    position: "left" // or "right"
                },
                xaxes: [],
                yaxes: [],
                series: {
                    points: {
                        show: false,
                        radius: 3,
                        lineWidth: 2, // in pixels
                        fill: true,
                        fillColor: "#ffffff",
                        symbol: "circle" // or callback
                    },
                    lines: {
                        // we don't put in show: false so we can see
                        // whether lines were actively disabled
                        lineWidth: 2, // in pixels
                        fill: false,
                        fillColor: null,
                        steps: false
                        // Omit 'zero', so we can later default its value to
                        // match that of the 'fill' option.
                    },
                    bars: {
                        show: false,
                        lineWidth: 2, // in pixels
                        barWidth: 1, // in units of the x axis
                        fill: true,
                        fillColor: null,
                        align: "left", // "left", "right", or "center"
                        horizontal: false,
                        zero: true
                    },
                    shadowSize: 3,
                    highlightColor: null
                },
                grid: {
                    show: true,
                    aboveData: false,
                    color: "#545454", // primary color used for outline and labels
                    backgroundColor: null, // null for transparent, else color
                    borderColor: null, // set if different from the grid color
                    tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
                    margin: 0, // distance from the canvas edge to the grid
                    labelMargin: 5, // in pixels
                    eventSectionHeight: 0, // space for event section
                    axisMargin: 8, // in pixels
                    borderWidth: 2, // in pixels
                    minBorderMargin: null, // in pixels, null means taken from points radius
                    markings: null, // array of ranges or fn: axes -> array of ranges
                    markingsColor: "#f4f4f4",
                    markingsLineWidth: 2,
                    // interactive stuff
                    clickable: false,
                    hoverable: false,
                    autoHighlight: true, // highlight in case mouse is near
                    mouseActiveRadius: 10 // how far the mouse can be away to activate an item
                },
                interaction: {
                    redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
                },
                hooks: {}
            },
        surface = null,     // the canvas for the plot itself
        overlay = null,     // canvas for interactive stuff on top of plot
        eventHolder = null, // jQuery object that events should be bound to
        ctx = null, octx = null,
        xaxes = [], yaxes = [],
        plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
        plotWidth = 0, plotHeight = 0,
        hooks = {
            processOptions: [],
            processRawData: [],
            processDatapoints: [],
            processOffset: [],
            processRange: [],
            drawBackground: [],
            drawSeries: [],
            draw: [],
            bindEvents: [],
            drawOverlay: [],
            shutdown: []
        },
        plot = this;

        // public functions
        plot.setData = setData;
        plot.setupGrid = setupGrid;
        plot.draw = draw;
        plot.getPlaceholder = function() { return placeholder; };
        plot.getCanvas = function() { return surface.element; };
        plot.getPlotOffset = function() { return plotOffset; };
        plot.width = function () { return plotWidth; };
        plot.height = function () { return plotHeight; };
        plot.offset = function () {
            var o = eventHolder.offset();
            o.left += plotOffset.left;
            o.top += plotOffset.top;
            return o;
        };
        plot.getData = function () { return series; };
        plot.getAxes = function () {
            var res = {}, i;
            $.each(xaxes.concat(yaxes), function (_, axis) {
                if (axis)
                    res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
            });
            return res;
        };
        plot.getXAxes = function () { return xaxes; };
        plot.getYAxes = function () { return yaxes; };
        plot.c2p = canvasToAxisCoords;
        plot.p2c = axisToCanvasCoords;
        plot.getOptions = function () { return options; };
        plot.highlight = highlight;
        plot.unhighlight = unhighlight;
        plot.triggerRedrawOverlay = triggerRedrawOverlay;
        plot.pointOffset = function(point) {
            return {
                left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
                top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
            };
        };
        plot.shutdown = shutdown;
        plot.destroy = function () {
            shutdown();
            placeholder.removeData("plot").empty();

            series = [];
            options = null;
            surface = null;
            overlay = null;
            eventHolder = null;
            ctx = null;
            octx = null;
            xaxes = [];
            yaxes = [];
            hooks = null;
            highlights = [];
            plot = null;
        };
        plot.resize = function () {
        	var width = placeholder.width(),
        		height = placeholder.height();
            surface.resize(width, height);
            overlay.resize(width, height);
        };

        // public attributes
        plot.hooks = hooks;

        // initialize
        initPlugins(plot);
        parseOptions(options_);
        setupCanvases();
        setData(data_);
        setupGrid();
        draw();
        bindEvents();


        function executeHooks(hook, args) {
            args = [plot].concat(args);
            for (var i = 0; i < hook.length; ++i)
                hook[i].apply(this, args);
        }

        function initPlugins() {

            // References to key classes, allowing plugins to modify them

            var classes = {
                Canvas: Canvas
            };

            for (var i = 0; i < plugins.length; ++i) {
                var p = plugins[i];
                p.init(plot, classes);
                if (p.options)
                    $.extend(true, options, p.options);
            }
        }

        function parseOptions(opts) {

            $.extend(true, options, opts);

            // $.extend merges arrays, rather than replacing them.  When less
            // colors are provided than the size of the default palette, we
            // end up with those colors plus the remaining defaults, which is
            // not expected behavior; avoid it by replacing them here.

            if (opts && opts.colors) {
            	options.colors = opts.colors;
            }

            if (options.xaxis.color == null)
                options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
            if (options.yaxis.color == null)
                options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();

            if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
                options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
            if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
                options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;

            if (options.grid.borderColor == null)
                options.grid.borderColor = options.grid.color;
            if (options.grid.tickColor == null)
                options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();

            // Fill in defaults for axis options, including any unspecified
            // font-spec fields, if a font-spec was provided.

            // If no x/y axis options were provided, create one of each anyway,
            // since the rest of the code assumes that they exist.

            var i, axisOptions, axisCount,
                fontSize = placeholder.css("font-size"),
                fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
                fontDefaults = {
                    style: placeholder.css("font-style"),
                    size: Math.round(0.8 * fontSizeDefault),
                    variant: placeholder.css("font-variant"),
                    weight: placeholder.css("font-weight"),
                    family: placeholder.css("font-family")
                };

            axisCount = options.xaxes.length || 1;
            for (i = 0; i < axisCount; ++i) {

                axisOptions = options.xaxes[i];
                if (axisOptions && !axisOptions.tickColor) {
                    axisOptions.tickColor = axisOptions.color;
                }

                axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
                options.xaxes[i] = axisOptions;

                if (axisOptions.font) {
                    axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
                    if (!axisOptions.font.color) {
                        axisOptions.font.color = axisOptions.color;
                    }
                    if (!axisOptions.font.lineHeight) {
                        axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
                    }
                }
            }

            axisCount = options.yaxes.length || 1;
            for (i = 0; i < axisCount; ++i) {

                axisOptions = options.yaxes[i];
                if (axisOptions && !axisOptions.tickColor) {
                    axisOptions.tickColor = axisOptions.color;
                }

                axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
                options.yaxes[i] = axisOptions;

                if (axisOptions.font) {
                    axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
                    if (!axisOptions.font.color) {
                        axisOptions.font.color = axisOptions.color;
                    }
                    if (!axisOptions.font.lineHeight) {
                        axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
                    }
                }
            }

            // backwards compatibility, to be removed in future
            if (options.xaxis.noTicks && options.xaxis.ticks == null)
                options.xaxis.ticks = options.xaxis.noTicks;
            if (options.yaxis.noTicks && options.yaxis.ticks == null)
                options.yaxis.ticks = options.yaxis.noTicks;
            if (options.x2axis) {
                options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
                options.xaxes[1].position = "top";
                // Override the inherit to allow the axis to auto-scale
                if (options.x2axis.min == null) {
                    options.xaxes[1].min = null;
                }
                if (options.x2axis.max == null) {
                    options.xaxes[1].max = null;
                }
            }
            if (options.y2axis) {
                options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
                options.yaxes[1].position = "right";
                // Override the inherit to allow the axis to auto-scale
                if (options.y2axis.min == null) {
                    options.yaxes[1].min = null;
                }
                if (options.y2axis.max == null) {
                    options.yaxes[1].max = null;
                }
            }
            if (options.grid.coloredAreas)
                options.grid.markings = options.grid.coloredAreas;
            if (options.grid.coloredAreasColor)
                options.grid.markingsColor = options.grid.coloredAreasColor;
            if (options.lines)
                $.extend(true, options.series.lines, options.lines);
            if (options.points)
                $.extend(true, options.series.points, options.points);
            if (options.bars)
                $.extend(true, options.series.bars, options.bars);
            if (options.shadowSize != null)
                options.series.shadowSize = options.shadowSize;
            if (options.highlightColor != null)
                options.series.highlightColor = options.highlightColor;

            // save options on axes for future reference
            for (i = 0; i < options.xaxes.length; ++i)
                getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
            for (i = 0; i < options.yaxes.length; ++i)
                getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];

            // add hooks from options
            for (var n in hooks)
                if (options.hooks[n] && options.hooks[n].length)
                    hooks[n] = hooks[n].concat(options.hooks[n]);

            executeHooks(hooks.processOptions, [options]);
        }

        function setData(d) {
            series = parseData(d);
            fillInSeriesOptions();
            processData();
        }

        function parseData(d) {
            var res = [];
            for (var i = 0; i < d.length; ++i) {
                var s = $.extend(true, {}, options.series);

                if (d[i].data != null) {
                    s.data = d[i].data; // move the data instead of deep-copy
                    delete d[i].data;

                    $.extend(true, s, d[i]);

                    d[i].data = s.data;
                }
                else
                    s.data = d[i];
                res.push(s);
            }

            return res;
        }

        function axisNumber(obj, coord) {
            var a = obj[coord + "axis"];
            if (typeof a == "object") // if we got a real axis, extract number
                a = a.n;
            if (typeof a != "number")
                a = 1; // default to first axis
            return a;
        }

        function allAxes() {
            // return flat array without annoying null entries
            return $.grep(xaxes.concat(yaxes), function (a) { return a; });
        }

        function canvasToAxisCoords(pos) {
            // return an object with x/y corresponding to all used axes
            var res = {}, i, axis;
            for (i = 0; i < xaxes.length; ++i) {
                axis = xaxes[i];
                if (axis)
                    res["x" + axis.n] = axis.c2p(pos.left);
            }

            for (i = 0; i < yaxes.length; ++i) {
                axis = yaxes[i];
                if (axis)
                    res["y" + axis.n] = axis.c2p(pos.top);
            }

            if (res.x1 !== undefined)
                res.x = res.x1;
            if (res.y1 !== undefined)
                res.y = res.y1;

            return res;
        }

        function axisToCanvasCoords(pos) {
            // get canvas coords from the first pair of x/y found in pos
            var res = {}, i, axis, key;

            for (i = 0; i < xaxes.length; ++i) {
                axis = xaxes[i];
                if (axis && axis.used) {
                    key = "x" + axis.n;
                    if (pos[key] == null && axis.n == 1)
                        key = "x";

                    if (pos[key] != null) {
                        res.left = axis.p2c(pos[key]);
                        break;
                    }
                }
            }

            for (i = 0; i < yaxes.length; ++i) {
                axis = yaxes[i];
                if (axis && axis.used) {
                    key = "y" + axis.n;
                    if (pos[key] == null && axis.n == 1)
                        key = "y";

                    if (pos[key] != null) {
                        res.top = axis.p2c(pos[key]);
                        break;
                    }
                }
            }

            return res;
        }

        function getOrCreateAxis(axes, number) {
            if (!axes[number - 1])
                axes[number - 1] = {
                    n: number, // save the number for future reference
                    direction: axes == xaxes ? "x" : "y",
                    options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
                };

            return axes[number - 1];
        }

        function fillInSeriesOptions() {

            var neededColors = series.length, maxIndex = -1, i;

            // Subtract the number of series that already have fixed colors or
            // color indexes from the number that we still need to generate.

            for (i = 0; i < series.length; ++i) {
                var sc = series[i].color;
                if (sc != null) {
                    neededColors--;
                    if (typeof sc == "number" && sc > maxIndex) {
                        maxIndex = sc;
                    }
                }
            }

            // If any of the series have fixed color indexes, then we need to
            // generate at least as many colors as the highest index.

            if (neededColors <= maxIndex) {
                neededColors = maxIndex + 1;
            }

            // Generate all the colors, using first the option colors and then
            // variations on those colors once they're exhausted.

            var c, colors = [], colorPool = options.colors,
                colorPoolSize = colorPool.length, variation = 0;

            for (i = 0; i < neededColors; i++) {

                c = $.color.parse(colorPool[i % colorPoolSize] || "#666");

                // Each time we exhaust the colors in the pool we adjust
                // a scaling factor used to produce more variations on
                // those colors. The factor alternates negative/positive
                // to produce lighter/darker colors.

                // Reset the variation after every few cycles, or else
                // it will end up producing only white or black colors.

                if (i % colorPoolSize == 0 && i) {
                    if (variation >= 0) {
                        if (variation < 0.5) {
                            variation = -variation - 0.2;
                        } else variation = 0;
                    } else variation = -variation;
                }

                colors[i] = c.scale('rgb', 1 + variation);
            }

            // Finalize the series options, filling in their colors

            var colori = 0, s;
            for (i = 0; i < series.length; ++i) {
                s = series[i];

                // assign colors
                if (s.color == null) {
                    s.color = colors[colori].toString();
                    ++colori;
                }
                else if (typeof s.color == "number")
                    s.color = colors[s.color].toString();

                // turn on lines automatically in case nothing is set
                if (s.lines.show == null) {
                    var v, show = true;
                    for (v in s)
                        if (s[v] && s[v].show) {
                            show = false;
                            break;
                        }
                    if (show)
                        s.lines.show = true;
                }

                // If nothing was provided for lines.zero, default it to match
                // lines.fill, since areas by default should extend to zero.

                if (s.lines.zero == null) {
                    s.lines.zero = !!s.lines.fill;
                }

                // setup axes
                s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
                s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
            }
        }

        function processData() {
            var topSentry = Number.POSITIVE_INFINITY,
                bottomSentry = Number.NEGATIVE_INFINITY,
                fakeInfinity = Number.MAX_VALUE,
                i, j, k, m, length,
                s, points, ps, x, y, axis, val, f, p,
                data, format;

            function updateAxis(axis, min, max) {
                if (min < axis.datamin && min != -fakeInfinity)
                    axis.datamin = min;
                if (max > axis.datamax && max != fakeInfinity)
                    axis.datamax = max;
            }

            $.each(allAxes(), function (_, axis) {
                // init axis
                axis.datamin = topSentry;
                axis.datamax = bottomSentry;
                axis.used = false;
            });

            for (i = 0; i < series.length; ++i) {
                s = series[i];
                s.datapoints = { points: [] };

                executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
            }

            // first pass: clean and copy data
            for (i = 0; i < series.length; ++i) {
                s = series[i];

                data = s.data;
                format = s.datapoints.format;

                if (!format) {
                    format = [];
                    // find out how to copy
                    format.push({ x: true, number: true, required: true });
                    format.push({ y: true, number: true, required: true });

                    if (s.stack || s.bars.show || (s.lines.show && s.lines.fill)) {
                        var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
                        format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
                        if (s.bars.horizontal) {
                            delete format[format.length - 1].y;
                            format[format.length - 1].x = true;
                        }
                    }

                    s.datapoints.format = format;
                }

                if (s.datapoints.pointsize != null)
                    continue; // already filled in

                s.datapoints.pointsize = format.length;

                ps = s.datapoints.pointsize;
                points = s.datapoints.points;

                var insertSteps = s.lines.show && s.lines.steps;
                s.xaxis.used = s.yaxis.used = true;

                for (j = k = 0; j < data.length; ++j, k += ps) {
                    p = data[j];

                    var nullify = p == null;
                    if (!nullify) {
                        for (m = 0; m < ps; ++m) {
                            val = p[m];
                            f = format[m];

                            if (f) {
                                if (f.number && val != null) {
                                    val = +val; // convert to number
                                    if (isNaN(val))
                                        val = null;
                                    else if (val == Infinity)
                                        val = fakeInfinity;
                                    else if (val == -Infinity)
                                        val = -fakeInfinity;
                                }

                                if (val == null) {
                                    if (f.required)
                                        nullify = true;

                                    if (f.defaultValue != null)
                                        val = f.defaultValue;
                                }
                            }

                            points[k + m] = val;
                        }
                    }

                    if (nullify) {
                        for (m = 0; m < ps; ++m) {
                            val = points[k + m];
                            if (val != null) {
                                f = format[m];
                                // extract min/max info
                                if (f.autoscale !== false) {
                                    if (f.x) {
                                        updateAxis(s.xaxis, val, val);
                                    }
                                    if (f.y) {
                                        updateAxis(s.yaxis, val, val);
                                    }
                                }
                            }
                            points[k + m] = null;
                        }
                    }

                    if (insertSteps && k > 0 && (!nullify || points[k - ps] != null)) {
                        // copy the point to make room for a middle point
                        for (m = 0; m < ps; ++m)
                            points[k + ps + m] = points[k + m];

                        // middle point has same y
                        points[k + 1] = points[k - ps + 1] || 0;

                        // if series has null values, let's give the last !null value a nice step
                        if(nullify)
                        	points[k] = p[0];

                        // we've added a point, better reflect that
                        k += ps;
                    }
                }
            }

            // give the hooks a chance to run
            for (i = 0; i < series.length; ++i) {
                s = series[i];
                points = s.datapoints.points;
                ps = s.datapoints.pointsize;

                // grafana
                if (s.transform === 'negative-Y') {
                  for (j = 0; j < points.length; j += ps) {
                    if (points[j] == null)
                        continue;

                      val = points[j + 1];
                      points[j + 1] = -val;
                  }
                }

                executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
            }

            // second pass: find datamax/datamin for auto-scaling
            for (i = 0; i < series.length; ++i) {
                s = series[i];
                points = s.datapoints.points;
                ps = s.datapoints.pointsize;
                format = s.datapoints.format;

                var xmin = topSentry, ymin = topSentry,
                    xmax = bottomSentry, ymax = bottomSentry;

                for (j = 0; j < points.length; j += ps) {
                    if (points[j] == null)
                        continue;

                    for (m = 0; m < ps; ++m) {
                        val = points[j + m];
                        f = format[m];
                        if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
                            continue;

                        if (f.x) {
                            if (val < xmin)
                                xmin = val;
                            if (val > xmax)
                                xmax = val;
                        }
                        if (f.y) {
                            if (val < ymin)
                                ymin = val;
                            if (val > ymax)
                                ymax = val;
                        }
                    }
                }

                if (s.bars.show) {
                    // make sure we got room for the bar on the dancing floor
                    var delta;

                    switch (s.bars.align) {
                        case "left":
                            delta = 0;
                            break;
                        case "right":
                            delta = -s.bars.barWidth;
                            break;
                        default:
                            delta = -s.bars.barWidth / 2;
                    }

                    if (s.bars.horizontal) {
                        ymin += delta;
                        ymax += delta + s.bars.barWidth;
                    }
                    else {
                        xmin += delta;
                        xmax += delta + s.bars.barWidth;
                    }
                }

                updateAxis(s.xaxis, xmin, xmax);
                updateAxis(s.yaxis, ymin, ymax);
            }

            $.each(allAxes(), function (_, axis) {
                if (axis.datamin == topSentry)
                    axis.datamin = null;
                if (axis.datamax == bottomSentry)
                    axis.datamax = null;
            });
        }

        function setupCanvases() {
            // Make sure the placeholder is clear of everything except canvases
            // from a previous plot in this container that we'll try to re-use.

            placeholder.find(".flot-temp-elem").remove();

            if (placeholder.css("position") == 'static')
                placeholder.css("position", "relative"); // for positioning labels and overlay

            surface = new Canvas("flot-base", placeholder);
            overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features

            ctx = surface.context;
            octx = overlay.context;

            // define which element we're listening for events on
            eventHolder = $(overlay.element).unbind();

            // If we're re-using a plot object, shut down the old one

            var existing = placeholder.data("plot");

            if (existing) {
                existing.shutdown();
                overlay.clear();
            }

            // save in case we get replotted
            placeholder.data("plot", plot);
        }

        function bindEvents() {
            // bind events
            if (options.grid.hoverable) {
                eventHolder.mousemove(onMouseMove);

                // Use bind, rather than .mouseleave, because we officially
                // still support jQuery 1.2.6, which doesn't define a shortcut
                // for mouseenter or mouseleave.  This was a bug/oversight that
                // was fixed somewhere around 1.3.x.  We can return to using
                // .mouseleave when we drop support for 1.2.6.

                eventHolder.bind("mouseleave", onMouseLeave);
            }

            if (options.grid.clickable)
                eventHolder.click(onClick);

            executeHooks(hooks.bindEvents, [eventHolder]);
        }

        function shutdown() {
            if (redrawTimeout)
                clearTimeout(redrawTimeout);

            eventHolder.unbind("mousemove", onMouseMove);
            eventHolder.unbind("mouseleave", onMouseLeave);
            eventHolder.unbind("click", onClick);

            executeHooks(hooks.shutdown, [eventHolder]);
        }

        function setTransformationHelpers(axis) {
            // set helper functions on the axis, assumes plot area
            // has been computed already

            function identity(x) { return x; }

            var s, m, t = axis.options.transform || identity,
                it = axis.options.inverseTransform;

            // precompute how much the axis is scaling a point
            // in canvas space
            if (axis.direction == "x") {
                s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
                m = Math.min(t(axis.max), t(axis.min));
            }
            else {
                s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
                s = -s;
                m = Math.max(t(axis.max), t(axis.min));
            }

            // data point to canvas coordinate
            if (t == identity) // slight optimization
                axis.p2c = function (p) { return (p - m) * s; };
            else
                axis.p2c = function (p) { return (t(p) - m) * s; };
            // canvas coordinate to data point
            if (!it)
                axis.c2p = function (c) { return m + c / s; };
            else
                axis.c2p = function (c) { return it(m + c / s); };
        }

        function measureTickLabels(axis) {

            var opts = axis.options,
                ticks = axis.ticks || [],
                labelWidth = opts.labelWidth || 0,
                labelHeight = opts.labelHeight || 0,
                maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null),
                legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
                layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
                font = opts.font || "flot-tick-label tickLabel";

            for (var i = 0; i < ticks.length; ++i) {

                var t = ticks[i];

                if (!t.label)
                    continue;

                var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);

                /// Grafana fix, add +1 to label width
                labelWidth = Math.max(labelWidth, info.width + 1);
                labelHeight = Math.max(labelHeight, info.height);
            }

            axis.labelWidth = opts.labelWidth || labelWidth;
            axis.labelHeight = opts.labelHeight || labelHeight;
        }

        function allocateAxisBoxFirstPhase(axis) {
            // find the bounding box of the axis by looking at label
            // widths/heights and ticks, make room by diminishing the
            // plotOffset; this first phase only looks at one
            // dimension per axis, the other dimension depends on the
            // other axes so will have to wait

            var lw = axis.labelWidth,
                lh = axis.labelHeight,
                pos = axis.options.position,
                isXAxis = axis.direction === "x",
                tickLength = axis.options.tickLength,
                axisMargin = options.grid.axisMargin,
                padding = options.grid.labelMargin,
                eventSectionPadding = options.grid.eventSectionHeight,
                innermost = true,
                outermost = true,
                first = true,
                found = false;

            // Determine the axis's position in its direction and on its side

            $.each(isXAxis ? xaxes : yaxes, function(i, a) {
                if (a && (a.show || a.reserveSpace)) {
                    if (a === axis) {
                        found = true;
                    } else if (a.options.position === pos) {
                        if (found) {
                            outermost = false;
                        } else {
                            innermost = false;
                        }
                    }
                    if (!found) {
                        first = false;
                    }
                }
            });

            // The outermost axis on each side has no margin

            if (outermost) {
                axisMargin = 0;
            }

            // The ticks for the first axis in each direction stretch across

            if (tickLength == null) {
                tickLength = first ? "full" : 5;
            }

            if (!isNaN(+tickLength))
                padding += +tickLength;

            if (isXAxis) {
                // Add space for event section
                lh += padding;
                lh += eventSectionPadding;

                if (pos == "bottom") {
                    plotOffset.bottom += lh + axisMargin;
                    axis.box = { top: surface.height - plotOffset.bottom, height: lh };
                }
                else {
                    axis.box = { top: plotOffset.top + axisMargin, height: lh };
                    plotOffset.top += lh + axisMargin;
                }
            }
            else {
                lw += padding;

                if (pos == "left") {
                    axis.box = { left: plotOffset.left + axisMargin, width: lw };
                    plotOffset.left += lw + axisMargin;
                }
                else {
                    plotOffset.right += lw + axisMargin;
                    axis.box = { left: surface.width - plotOffset.right, width: lw };
                }
            }

             // save for future reference
            axis.position = pos;
            axis.tickLength = tickLength;
            axis.box.padding = padding;
            axis.box.eventSectionPadding = eventSectionPadding;
            axis.innermost = innermost;
        }

        function allocateAxisBoxSecondPhase(axis) {
            // now that all axis boxes have been placed in one
            // dimension, we can set the remaining dimension coordinates
            if (axis.direction == "x") {
                axis.box.left = plotOffset.left - axis.labelWidth / 2;
                axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
            }
            else {
                axis.box.top = plotOffset.top - axis.labelHeight / 2;
                axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
            }
        }

        function adjustLayoutForThingsStickingOut() {
            // possibly adjust plot offset to ensure everything stays
            // inside the canvas and isn't clipped off

            var minMargin = options.grid.minBorderMargin,
                axis, i;

            // check stuff from the plot (FIXME: this should just read
            // a value from the series, otherwise it's impossible to
            // customize)
            if (minMargin == null) {
                minMargin = 0;
                for (i = 0; i < series.length; ++i)
                    minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
            }

            var margins = {
                left: minMargin,
                right: minMargin,
                top: minMargin,
                bottom: minMargin
            };

            // check axis labels, note we don't check the actual
            // labels but instead use the overall width/height to not
            // jump as much around with replots
            $.each(allAxes(), function (_, axis) {
                if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
                    if (axis.direction === "x") {
                        margins.left = Math.max(margins.left, axis.labelWidth / 2);
                        margins.right = Math.max(margins.right, axis.labelWidth / 2);
                    } else {
                        margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
                        margins.top = Math.max(margins.top, axis.labelHeight / 2);
                    }
                }
            });

            plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
            plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
            plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
            plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
        }

        function setupGrid() {
            var i, axes = allAxes(), showGrid = options.grid.show;

            // Initialize the plot's offset from the edge of the canvas

            for (var a in plotOffset) {
                var margin = options.grid.margin || 0;
                plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
            }

            executeHooks(hooks.processOffset, [plotOffset]);

            // If the grid is visible, add its border width to the offset

            for (var a in plotOffset) {
                if(typeof(options.grid.borderWidth) == "object") {
                    plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
                }
                else {
                    plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
                }
            }

            $.each(axes, function (_, axis) {
                var axisOpts = axis.options;
                axis.show = axisOpts.show == null ? axis.used : axisOpts.show;
                axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace;
                setRange(axis);
            });

            executeHooks(hooks.processRange, []);

            if (showGrid) {

                var allocatedAxes = $.grep(axes, function (axis) {
                    return axis.show || axis.reserveSpace;
                });

                var snaped = false;
                for (var i = 0; i < 2; i++) {
                    $.each(allocatedAxes, function (_, axis) {
                        // make the ticks
                        setupTickGeneration(axis);
                        setTicks(axis);
                        snaped = snapRangeToTicks(axis, axis.ticks) || snaped;
                        // find labelWidth/Height for axis
                        measureTickLabels(axis);
                    });

                    if (snaped && hooks.processRange.length > 0) {
                        executeHooks(hooks.processRange, []);
                        snaped = false;
                    } else {
                        break;
                    }
                }

                // with all dimensions calculated, we can compute the
                // axis bounding boxes, start from the outside
                // (reverse order)
                for (i = allocatedAxes.length - 1; i >= 0; --i)
                    allocateAxisBoxFirstPhase(allocatedAxes[i]);

                // make sure we've got enough space for things that
                // might stick out
                adjustLayoutForThingsStickingOut();

                $.each(allocatedAxes, function (_, axis) {
                    allocateAxisBoxSecondPhase(axis);
                });
            }


            plotWidth = surface.width - plotOffset.left - plotOffset.right;
            plotHeight = surface.height - plotOffset.bottom - plotOffset.top;

            // now we got the proper plot dimensions, we can compute the scaling
            $.each(axes, function (_, axis) {
                setTransformationHelpers(axis);
            });

            if (showGrid) {
                drawAxisLabels();
            }

            insertLegend();
        }

        function setRange(axis) {
            var opts = axis.options,
                min = +(opts.min != null ? opts.min : axis.datamin),
                max = +(opts.max != null ? opts.max : axis.datamax),
                delta = max - min;

            if (delta == 0.0) {
                // Grafana fix: wide Y min and max using increased wideFactor
                // when all series values are the same
                var wideFactor = 0.25;
                var widen = Math.abs(max == 0 ? 1 : max * wideFactor);

                if (opts.min == null) {
                  min -= widen;
                }
                // always widen max if we couldn't widen min to ensure we
                // don't fall into min == max which doesn't work
                if (opts.max == null || opts.min != null) {
                  max += widen;
                }
            }
            else {
                // consider autoscaling
                var margin = opts.autoscaleMargin;
                if (margin != null) {
                    if (opts.min == null) {
                        min -= delta * margin;
                        // make sure we don't go below zero if all values
                        // are positive
                        if (min < 0 && axis.datamin != null && axis.datamin >= 0)
                            min = 0;
                    }
                    if (opts.max == null) {
                        max += delta * margin;
                        if (max > 0 && axis.datamax != null && axis.datamax <= 0)
                            max = 0;
                    }
                }
            }
            axis.min = min;
            axis.max = max;
        }

        // grafana change
        function getSignificantDigitCount(n) {
          //remove decimal and make positive
          n = Math.abs(String(n).replace(".", ""));
          if (n == 0) {
            return 0;
          }

          // kill the 0s at the end of n
          while (n != 0 && n % 10 == 0) {
            n /= 10;
          }

          // get number of digits
          return Math.floor(Math.log(n) / Math.LN10) + 1;
        }

        function setupTickGeneration(axis) {
            var opts = axis.options;

            // estimate number of ticks
            var noTicks;
            if (typeof opts.ticks == "number" && opts.ticks > 0)
                noTicks = opts.ticks;
            else
                // heuristic based on the model a*sqrt(x) fitted to
                // some data points that seemed reasonable
                noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);

            var delta = (axis.max - axis.min) / noTicks,
                dec = -Math.floor(Math.log(delta) / Math.LN10),
                maxDec = opts.tickDecimals;

            if (maxDec != null && dec > maxDec) {
                dec = maxDec;
            }

            var magn = Math.pow(10, -dec),
                norm = delta / magn, // norm is between 1.0 and 10.0
                size;

            if (norm < 1.5) {
                size = 1;
            } else if (norm < 3) {
                size = 2;
                // special case for 2.5, requires an extra decimal
                if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
                    size = 2.5;
                    ++dec;
                }
            } else if (norm < 7.5) {
                size = 5;
            } else {
                size = 10;
            }

            size *= magn;

            if (opts.minTickSize != null && size < opts.minTickSize) {
                size = opts.minTickSize;
            }

            axis.delta = delta;
            axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
            axis.tickSize = opts.tickSize || size;

            // grafana addition
            if (opts.tickDecimals === null || opts.tickDecimals === undefined) {
              axis.scaledDecimals = axis.tickDecimals + dec;
            }

            // Time mode was moved to a plug-in in 0.8, and since so many people use it
            // we'll add an especially friendly reminder to make sure they included it.

            if (opts.mode == "time" && !axis.tickGenerator) {
                throw new Error("Time mode requires the flot.time plugin.");
            }

            // Flot supports base-10 axes; any other mode else is handled by a plug-in,
            // like flot.time.js.

            if (!axis.tickGenerator) {

                axis.tickGenerator = function (axis) {

                    var ticks = [],
                        start = floorInBase(axis.min, axis.tickSize),
                        i = 0,
                        v = Number.NaN,
                        prev;

                    do {
                        prev = v;
                        v = start + i * axis.tickSize;
                        ticks.push(v);
                        ++i;
                    } while (v < axis.max && v != prev);
                    return ticks;
                };

				axis.tickFormatter = function (value, axis) {

					var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
					var formatted = "" + Math.round(value * factor) / factor;

					// If tickDecimals was specified, ensure that we have exactly that
					// much precision; otherwise default to the value's own precision.

					if (axis.tickDecimals != null) {
						var decimal = formatted.indexOf(".");
						var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
						if (precision < axis.tickDecimals) {
							return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
						}
					}

                    return formatted;
                };
            }

            if ($.isFunction(opts.tickFormatter))
                axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };

            if (opts.alignTicksWithAxis != null) {
                var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
                if (otherAxis && otherAxis.used && otherAxis != axis) {
                    // consider snapping min/max to outermost nice ticks
                    var niceTicks = axis.tickGenerator(axis);
                    if (niceTicks.length > 0) {
                        if (opts.min == null)
                            axis.min = Math.min(axis.min, niceTicks[0]);
                        if (opts.max == null && niceTicks.length > 1)
                            axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
                    }

                    axis.tickGenerator = function (axis) {
                        // copy ticks, scaled to this axis
                        var ticks = [], v, i;
                        for (i = 0; i < otherAxis.ticks.length; ++i) {
                            v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
                            v = axis.min + v * (axis.max - axis.min);
                            ticks.push(v);
                        }
                        return ticks;
                    };

                    // we might need an extra decimal since forced
                    // ticks don't necessarily fit naturally
                    if (!axis.mode && opts.tickDecimals == null) {
                        var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
                            ts = axis.tickGenerator(axis);

                        // only proceed if the tick interval rounded
                        // with an extra decimal doesn't give us a
                        // zero at end
                        if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
                            axis.tickDecimals = extraDec;
                    }
                }
            }
        }

        function setTicks(axis) {
            var oticks = axis.options.ticks, ticks = [];
            if (oticks == null || (typeof oticks == "number" && oticks > 0))
                ticks = axis.tickGenerator(axis);
            else if (oticks) {
                if ($.isFunction(oticks))
                    // generate the ticks
                    ticks = oticks(axis);
                else
                    ticks = oticks;
            }

            // clean up/labelify the supplied ticks, copy them over
            var i, v;
            axis.ticks = [];
            for (i = 0; i < ticks.length; ++i) {
                var label = null;
                var t = ticks[i];
                if (typeof t == "object") {
                    v = +t[0];
                    if (t.length > 1)
                        label = t[1];
                }
                else
                    v = +t;
                if (label == null)
                    label = axis.tickFormatter(v, axis);
                if (!isNaN(v))
                    axis.ticks.push({ v: v, label: label });
            }
        }

        function snapRangeToTicks(axis, ticks) {
            var changed = false;
            if (axis.options.autoscaleMargin && ticks.length > 0) {
                // snap to ticks
                if (axis.options.min == null) {
                    axis.min = Math.min(axis.min, ticks[0].v);
                    changed = true;
                }
                if (axis.options.max == null && ticks.length > 1) {
                    axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
                    changed = true;
                }
            }
            return changed;
        }

        function draw() {

            surface.clear();

            executeHooks(hooks.drawBackground, [ctx]);

            var grid = options.grid;

            // draw background, if any
            if (grid.show && grid.backgroundColor)
                drawBackground();

            if (grid.show && !grid.aboveData) {
                drawGrid();
            }

            for (var i = 0; i < series.length; ++i) {
                executeHooks(hooks.drawSeries, [ctx, series[i]]);
                drawSeries(series[i]);
            }

            executeHooks(hooks.draw, [ctx]);

            if (grid.show && grid.aboveData) {
                drawGrid();
            }

            surface.render();

            // A draw implies that either the axes or data have changed, so we
            // should probably update the overlay highlights as well.

            triggerRedrawOverlay();
        }

        function extractRange(ranges, coord) {
            var axis, from, to, key, axes = allAxes();

            for (var i = 0; i < axes.length; ++i) {
                axis = axes[i];
                if (axis.direction == coord) {
                    key = coord + axis.n + "axis";
                    if (!ranges[key] && axis.n == 1)
                        key = coord + "axis"; // support x1axis as xaxis
                    if (ranges[key]) {
                        from = ranges[key].from;
                        to = ranges[key].to;
                        break;
                    }
                }
            }

            // backwards-compat stuff - to be removed in future
            if (!ranges[key]) {
                axis = coord == "x" ? xaxes[0] : yaxes[0];
                from = ranges[coord + "1"];
                to = ranges[coord + "2"];
            }

            // auto-reverse as an added bonus
            if (from != null && to != null && from > to) {
                var tmp = from;
                from = to;
                to = tmp;
            }

            return { from: from, to: to, axis: axis };
        }

        function drawBackground() {
            ctx.save();
            ctx.translate(plotOffset.left, plotOffset.top);

            ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
            ctx.fillRect(0, 0, plotWidth, plotHeight);
            ctx.restore();
        }

        function drawGrid() {
            var i, axes, bw, bc;

            ctx.save();
            ctx.translate(plotOffset.left, plotOffset.top);

            // draw markings
            var markings = options.grid.markings;
            if (markings) {
                if ($.isFunction(markings)) {
                    axes = plot.getAxes();
                    // xmin etc. is backwards compatibility, to be
                    // removed in the future
                    axes.xmin = axes.xaxis.min;
                    axes.xmax = axes.xaxis.max;
                    axes.ymin = axes.yaxis.min;
                    axes.ymax = axes.yaxis.max;

                    markings = markings(axes);
                }

                for (i = 0; i < markings.length; ++i) {
                    var m = markings[i],
                        xrange = extractRange(m, "x"),
                        yrange = extractRange(m, "y");

                    // fill in missing
                    if (xrange.from == null)
                        xrange.from = xrange.axis.min;
                    if (xrange.to == null)
                        xrange.to = xrange.axis.max;
                    if (yrange.from == null)
                        yrange.from = yrange.axis.min;
                    if (yrange.to == null)
                        yrange.to = yrange.axis.max;

                    // clip
                    if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
                        yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
                        continue;

                    xrange.from = Math.max(xrange.from, xrange.axis.min);
                    xrange.to = Math.min(xrange.to, xrange.axis.max);
                    yrange.from = Math.max(yrange.from, yrange.axis.min);
                    yrange.to = Math.min(yrange.to, yrange.axis.max);

                    var xequal = xrange.from === xrange.to,
                        yequal = yrange.from === yrange.to;

                    if (xequal && yequal) {
                        continue;
                    }

                    // then draw
                    xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
                    xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
                    yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
                    yrange.to = Math.floor(yrange.axis.p2c(yrange.to));

                    if (xequal || yequal) {
                        var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
                            subPixel = lineWidth % 2 ? 0.5 : 0;
                        ctx.beginPath();
                        ctx.strokeStyle = m.color || options.grid.markingsColor;
                        ctx.lineWidth = lineWidth;
                        if (xequal) {
                            ctx.moveTo(xrange.to + subPixel, yrange.from);
                            ctx.lineTo(xrange.to + subPixel, yrange.to);
                        } else {
                            ctx.moveTo(xrange.from, yrange.to + subPixel);
                            ctx.lineTo(xrange.to, yrange.to + subPixel);
                        }
                        ctx.stroke();
                    } else {
                        ctx.fillStyle = m.color || options.grid.markingsColor;
                        ctx.fillRect(xrange.from, yrange.to,
                                     xrange.to - xrange.from,
                                     yrange.from - yrange.to);
                    }
                }
            }

            // draw the ticks
            axes = allAxes();
            bw = options.grid.borderWidth;

            for (var j = 0; j < axes.length; ++j) {
                var axis = axes[j], box = axis.box,
                    t = axis.tickLength, x, y, xoff, yoff;
                if (!axis.show || axis.ticks.length == 0)
                    continue;

                ctx.lineWidth = 1;

                // find the edges
                if (axis.direction == "x") {
                    x = 0;
                    if (t == "full")
                        y = (axis.position == "top" ? 0 : plotHeight);
                    else
                        y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
                }
                else {
                    y = 0;
                    if (t == "full")
                        x = (axis.position == "left" ? 0 : plotWidth);
                    else
                        x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
                }

                // draw tick bar
                if (!axis.innermost) {
                    ctx.strokeStyle = axis.options.color;
                    ctx.beginPath();
                    xoff = yoff = 0;
                    if (axis.direction == "x")
                        xoff = plotWidth + 1;
                    else
                        yoff = plotHeight + 1;

                    if (ctx.lineWidth == 1) {
                        if (axis.direction == "x") {
                            y = Math.floor(y) + 0.5;
                        } else {
                            x = Math.floor(x) + 0.5;
                        }
                    }

                    ctx.moveTo(x, y);
                    ctx.lineTo(x + xoff, y + yoff);
                    ctx.stroke();
                }

                // draw ticks

                ctx.strokeStyle = axis.options.tickColor;

                ctx.beginPath();
                for (i = 0; i < axis.ticks.length; ++i) {
                    var v = axis.ticks[i].v;

                    xoff = yoff = 0;

                    if (isNaN(v) || v < axis.min || v > axis.max
                        // skip those lying on the axes if we got a border
                        || (t == "full"
                            && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
                            && (v == axis.min || v == axis.max)))
                        continue;

                    if (axis.direction == "x") {
                        x = axis.p2c(v);
                        yoff = t == "full" ? -plotHeight : t;

                        if (axis.position == "top")
                            yoff = -yoff;
                    }
                    else {
                        y = axis.p2c(v);
                        xoff = t == "full" ? -plotWidth : t;

                        if (axis.position == "left")
                            xoff = -xoff;
                    }

                    if (ctx.lineWidth == 1) {
                        if (axis.direction == "x")
                            x = Math.floor(x) + 0.5;
                        else
                            y = Math.floor(y) + 0.5;
                    }

                    ctx.moveTo(x, y);
                    ctx.lineTo(x + xoff, y + yoff);
                }

                ctx.stroke();
            }


            // draw border
            if (bw) {
                // If either borderWidth or borderColor is an object, then draw the border
                // line by line instead of as one rectangle
                bc = options.grid.borderColor;
                if(typeof bw == "object" || typeof bc == "object") {
                    if (typeof bw !== "object") {
                        bw = {top: bw, right: bw, bottom: bw, left: bw};
                    }
                    if (typeof bc !== "object") {
                        bc = {top: bc, right: bc, bottom: bc, left: bc};
                    }

                    if (bw.top > 0) {
                        ctx.strokeStyle = bc.top;
                        ctx.lineWidth = bw.top;
                        ctx.beginPath();
                        ctx.moveTo(0 - bw.left, 0 - bw.top/2);
                        ctx.lineTo(plotWidth, 0 - bw.top/2);
                        ctx.stroke();
                    }

                    if (bw.right > 0) {
                        ctx.strokeStyle = bc.right;
                        ctx.lineWidth = bw.right;
                        ctx.beginPath();
                        ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
                        ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
                        ctx.stroke();
                    }

                    if (bw.bottom > 0) {
                        ctx.strokeStyle = bc.bottom;
                        ctx.lineWidth = bw.bottom;
                        ctx.beginPath();
                        ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
                        ctx.lineTo(0, plotHeight + bw.bottom / 2);
                        ctx.stroke();
                    }

                    if (bw.left > 0) {
                        ctx.strokeStyle = bc.left;
                        ctx.lineWidth = bw.left;
                        ctx.beginPath();
                        ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
                        ctx.lineTo(0- bw.left/2, 0);
                        ctx.stroke();
                    }
                }
                else {
                    ctx.lineWidth = bw;
                    ctx.strokeStyle = options.grid.borderColor;
                    ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
                }
            }

            ctx.restore();
        }

        function drawAxisLabels() {

            $.each(allAxes(), function (_, axis) {
                var box = axis.box,
                    legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
                    layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
                    font = axis.options.font || "flot-tick-label tickLabel",
                    tick, x, y, halign, valign;

                // Remove text before checking for axis.show and ticks.length;
                // otherwise plugins, like flot-tickrotor, that draw their own
                // tick labels will end up with both theirs and the defaults.

                surface.removeText(layer);

                if (!axis.show || axis.ticks.length == 0)
                    return;

                for (var i = 0; i < axis.ticks.length; ++i) {

                    tick = axis.ticks[i];
                    if (!tick.label || tick.v < axis.min || tick.v > axis.max)
                        continue;

                    if (axis.direction == "x") {
                        halign = "center";
                        x = plotOffset.left + axis.p2c(tick.v);
                        if (axis.position == "bottom") {
                            y = box.top + box.padding + box.eventSectionPadding;
                        } else {
                            y = box.top + box.height - box.padding;
                            valign = "bottom";
                        }
                    } else {
                        valign = "middle";
                        y = plotOffset.top + axis.p2c(tick.v);
                        if (axis.position == "left") {
                            x = box.left + box.width - box.padding;
                            halign = "right";
                        } else {
                            x = box.left + box.padding;
                        }
                    }

                    surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
                }
            });
        }

        function drawOrphanedPoints(series) {
            /* Filters series data for points with no neighbors before or after
             * and plots single 0.5 radius points for them so that they are displayed.
             */
            var abandonedPoints = [];
            var beforeX = null;
            var afterX = null;
            var datapoints = series.datapoints;
            // find any points with no neighbors before or after
            var emptyPoints = [];
            for (var j = 0; j < datapoints.pointsize - 2; j++) {
                emptyPoints.push(0);
            }
            for (var i = 0; i < datapoints.points.length; i += datapoints.pointsize) {
                var x = datapoints.points[i], y = datapoints.points[i + 1];
                if (i === datapoints.points.length - datapoints.pointsize) {
                    afterX = null;
                } else {
                    afterX = datapoints.points[i + datapoints.pointsize];
                }
                if (x !== null && y !== null && beforeX === null && afterX === null) {
                    abandonedPoints.push(x);
                    abandonedPoints.push(y);
                    abandonedPoints.push.apply(abandonedPoints, emptyPoints);
                }
                beforeX = x;

            }
            var olddatapoints = datapoints.points
            datapoints.points = abandonedPoints;

            series.points.radius = series.lines.lineWidth/2;
            // plot the orphan points with a radius of lineWidth/2
            drawSeriesPoints(series);
            // reset old info
            datapoints.points = olddatapoints;
        }

        function drawSeries(series) {
            if (series.lines.show) {
                drawSeriesLines(series);
                if (!series.points.show && !series.bars.show) {
                    // not necessary if user wants points displayed for everything
                    drawOrphanedPoints(series);
                }
            }
            if (series.bars.show)
                drawSeriesBars(series);
            if (series.points.show)
                drawSeriesPoints(series);
        }

        function drawSeriesLines(series) {
            function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
                var points = datapoints.points,
                    ps = datapoints.pointsize,
                    prevx = null, prevy = null;

                ctx.beginPath();
                for (var i = ps; i < points.length; i += ps) {
                    var x1 = points[i - ps], y1 = points[i - ps + 1],
                        x2 = points[i], y2 = points[i + 1];

                    if (x1 == null || x2 == null)
                        continue;

                    // clip with ymin
                    if (y1 <= y2 && y1 < axisy.min) {
                        if (y2 < axisy.min)
                            continue;   // line segment is outside
                        // compute new intersection point
                        x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y1 = axisy.min;
                    }
                    else if (y2 <= y1 && y2 < axisy.min) {
                        if (y1 < axisy.min)
                            continue;
                        x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y2 = axisy.min;
                    }

                    // clip with ymax
                    if (y1 >= y2 && y1 > axisy.max) {
                        if (y2 > axisy.max)
                            continue;
                        x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y1 = axisy.max;
                    }
                    else if (y2 >= y1 && y2 > axisy.max) {
                        if (y1 > axisy.max)
                            continue;
                        x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y2 = axisy.max;
                    }

                    // clip with xmin
                    if (x1 <= x2 && x1 < axisx.min) {
                        if (x2 < axisx.min)
                            continue;
                        y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x1 = axisx.min;
                    }
                    else if (x2 <= x1 && x2 < axisx.min) {
                        if (x1 < axisx.min)
                            continue;
                        y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x2 = axisx.min;
                    }

                    // clip with xmax
                    if (x1 >= x2 && x1 > axisx.max) {
                        if (x2 > axisx.max)
                            continue;
                        y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x1 = axisx.max;
                    }
                    else if (x2 >= x1 && x2 > axisx.max) {
                        if (x1 > axisx.max)
                            continue;
                        y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x2 = axisx.max;
                    }

                    if (x1 != prevx || y1 != prevy)
                        ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);

                    prevx = x2;
                    prevy = y2;
                    ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
                }
                ctx.stroke();
            }

            function plotLineArea(datapoints, axisx, axisy) {
                var points = datapoints.points,
                    ps = datapoints.pointsize,
                    bottom = Math.min(Math.max(0, axisy.min), axisy.max),
                    i = 0, top, areaOpen = false,
                    ypos = 1, segmentStart = 0, segmentEnd = 0;

                // we process each segment in two turns, first forward
                // direction to sketch out top, then once we hit the
                // end we go backwards to sketch the bottom
                while (true) {
                    if (ps > 0 && i > points.length + ps)
                        break;

                    i += ps; // ps is negative if going backwards

                    var x1 = points[i - ps],
                        y1 = points[i - ps + ypos],
                        x2 = points[i], y2 = points[i + ypos];

                    if (areaOpen) {
                        if (ps > 0 && x1 != null && x2 == null) {
                            // at turning point
                            segmentEnd = i;
                            ps = -ps;
                            ypos = 2;
                            continue;
                        }

                        if (ps < 0 && i == segmentStart + ps) {
                            // done with the reverse sweep
                            ctx.fill();
                            areaOpen = false;
                            ps = -ps;
                            ypos = 1;
                            i = segmentStart = segmentEnd + ps;
                            continue;
                        }
                    }

                    if (x1 == null || x2 == null)
                        continue;

                    // clip x values

                    // clip with xmin
                    if (x1 <= x2 && x1 < axisx.min) {
                        if (x2 < axisx.min)
                            continue;
                        y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x1 = axisx.min;
                    }
                    else if (x2 <= x1 && x2 < axisx.min) {
                        if (x1 < axisx.min)
                            continue;
                        y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x2 = axisx.min;
                    }

                    // clip with xmax
                    if (x1 >= x2 && x1 > axisx.max) {
                        if (x2 > axisx.max)
                            continue;
                        y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x1 = axisx.max;
                    }
                    else if (x2 >= x1 && x2 > axisx.max) {
                        if (x1 > axisx.max)
                            continue;
                        y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
                        x2 = axisx.max;
                    }

                    if (!areaOpen) {
                        // open area
                        ctx.beginPath();
                        ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
                        areaOpen = true;
                    }

                    // now first check the case where both is outside
                    if (y1 >= axisy.max && y2 >= axisy.max) {
                        ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
                        ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
                        continue;
                    }
                    else if (y1 <= axisy.min && y2 <= axisy.min) {
                        ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
                        ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
                        continue;
                    }

                    // else it's a bit more complicated, there might
                    // be a flat maxed out rectangle first, then a
                    // triangular cutout or reverse; to find these
                    // keep track of the current x values
                    var x1old = x1, x2old = x2;

                    // clip the y values, without shortcutting, we
                    // go through all cases in turn

                    // clip with ymin
                    if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
                        x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y1 = axisy.min;
                    }
                    else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
                        x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y2 = axisy.min;
                    }

                    // clip with ymax
                    if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
                        x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y1 = axisy.max;
                    }
                    else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
                        x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
                        y2 = axisy.max;
                    }

                    // if the x value was changed we got a rectangle
                    // to fill
                    if (x1 != x1old) {
                        ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
                        // it goes to (x1, y1), but we fill that below
                    }

                    // fill triangular section, this sometimes result
                    // in redundant points if (x1, y1) hasn't changed
                    // from previous line to, but we just ignore that
                    ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
                    ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));

                    // fill the other rectangle if it's there
                    if (x2 != x2old) {
                        ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
                        ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
                    }
                }
            }

            ctx.save();
            ctx.translate(plotOffset.left, plotOffset.top);
            ctx.lineJoin = "round";

            var lw = series.lines.lineWidth,
                sw = series.shadowSize;
            // FIXME: consider another form of shadow when filling is turned on
            if (lw > 0 && sw > 0) {
                // draw shadow as a thick and thin line with transparency
                ctx.lineWidth = sw;
                ctx.strokeStyle = "rgba(0,0,0,0.1)";
                // position shadow at angle from the mid of line
                var angle = Math.PI/18;
                plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
                ctx.lineWidth = sw/2;
                plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
            }

            ctx.lineWidth = lw;
            ctx.strokeStyle = series.color;
            var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
            if (fillStyle) {
                ctx.fillStyle = fillStyle;
                plotLineArea(series.datapoints, series.xaxis, series.yaxis);
            }

            if (lw > 0)
                plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
            ctx.restore();
        }

        function drawSeriesPoints(series) {
            function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
                var points = datapoints.points, ps = datapoints.pointsize;

                for (var i = 0; i < points.length; i += ps) {
                    var x = points[i], y = points[i + 1];
                    if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
                        continue;

                    ctx.beginPath();
                    x = axisx.p2c(x);
                    y = axisy.p2c(y) + offset;
                    if (symbol == "circle")
                        ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
                    else
                        symbol(ctx, x, y, radius, shadow);
                    ctx.closePath();

                    if (fillStyle) {
                        ctx.fillStyle = fillStyle;
                        ctx.fill();
                    }
                    ctx.stroke();
                }
            }

            ctx.save();
            ctx.translate(plotOffset.left, plotOffset.top);

            var lw = series.points.lineWidth,
                sw = series.shadowSize,
                radius = series.points.radius,
                symbol = series.points.symbol;

            // If the user sets the line width to 0, we change it to a very
            // small value. A line width of 0 seems to force the default of 1.
            // Doing the conditional here allows the shadow setting to still be
            // optional even with a lineWidth of 0.

            if( lw == 0 )
                lw = 0.0001;

            if (lw > 0 && sw > 0) {
                // draw shadow in two steps
                var w = sw / 2;
                ctx.lineWidth = w;
                ctx.strokeStyle = "rgba(0,0,0,0.1)";
                plotPoints(series.datapoints, radius, null, w + w/2, true,
                           series.xaxis, series.yaxis, symbol);

                ctx.strokeStyle = "rgba(0,0,0,0.2)";
                plotPoints(series.datapoints, radius, null, w/2, true,
                           series.xaxis, series.yaxis, symbol);
            }

            ctx.lineWidth = lw;
            ctx.strokeStyle = series.color;
            plotPoints(series.datapoints, radius,
                       getFillStyle(series.points, series.color), 0, false,
                       series.xaxis, series.yaxis, symbol);
            ctx.restore();
        }

        function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
            var left, right, bottom, top,
                drawLeft, drawRight, drawTop, drawBottom,
                tmp;

            // in horizontal mode, we start the bar from the left
            // instead of from the bottom so it appears to be
            // horizontal rather than vertical
            if (horizontal) {
                drawBottom = drawRight = drawTop = true;
                drawLeft = false;
                left = b;
                right = x;
                top = y + barLeft;
                bottom = y + barRight;

                // account for negative bars
                if (right < left) {
                    tmp = right;
                    right = left;
                    left = tmp;
                    drawLeft = true;
                    drawRight = false;
                }
            }
            else {
                drawLeft = drawRight = drawTop = true;
                drawBottom = false;
                left = x + barLeft;
                right = x + barRight;
                bottom = b;
                top = y;

                // account for negative bars
                if (top < bottom) {
                    tmp = top;
                    top = bottom;
                    bottom = tmp;
                    drawBottom = true;
                    drawTop = false;
                }
            }

            // clip
            if (right < axisx.min || left > axisx.max ||
                top < axisy.min || bottom > axisy.max)
                return;

            if (left < axisx.min) {
                left = axisx.min;
                drawLeft = false;
            }

            if (right > axisx.max) {
                right = axisx.max;
                drawRight = false;
            }

            if (bottom < axisy.min) {
                bottom = axisy.min;
                drawBottom = false;
            }

            if (top > axisy.max) {
                top = axisy.max;
                drawTop = false;
            }

            left = axisx.p2c(left);
            bottom = axisy.p2c(bottom);
            right = axisx.p2c(right);
            top = axisy.p2c(top);

            // fill the bar
            if (fillStyleCallback) {
                c.fillStyle = fillStyleCallback(bottom, top);
                c.fillRect(left, top, right - left, bottom - top)
            }

            // draw outline
            if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
                c.beginPath();

                // FIXME: inline moveTo is buggy with excanvas
                c.moveTo(left, bottom);
                if (drawLeft)
                    c.lineTo(left, top);
                else
                    c.moveTo(left, top);
                if (drawTop)
                    c.lineTo(right, top);
                else
                    c.moveTo(right, top);
                if (drawRight)
                    c.lineTo(right, bottom);
                else
                    c.moveTo(right, bottom);
                if (drawBottom)
                    c.lineTo(left, bottom);
                else
                    c.moveTo(left, bottom);
                c.stroke();
            }
        }

        function drawSeriesBars(series) {
            function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
                var points = datapoints.points, ps = datapoints.pointsize;

                for (var i = 0; i < points.length; i += ps) {
                    if (points[i] == null)
                        continue;
                    drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
                }
            }

            ctx.save();
            ctx.translate(plotOffset.left, plotOffset.top);

            // FIXME: figure out a way to add shadows (for instance along the right edge)
            ctx.lineWidth = series.bars.lineWidth;
            ctx.strokeStyle = series.color;

            var barLeft;

            switch (series.bars.align) {
                case "left":
                    barLeft = 0;
                    break;
                case "right":
                    barLeft = -series.bars.barWidth;
                    break;
                default:
                    barLeft = -series.bars.barWidth / 2;
            }

            var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
            plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
            ctx.restore();
        }

        function getFillStyle(filloptions, seriesColor, bottom, top) {
            var fill = filloptions.fill;
            if (!fill)
                return null;

            if (filloptions.fillColor)
                return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);

            var c = $.color.parse(seriesColor);
            c.a = typeof fill == "number" ? fill : 0.4;
            c.normalize();
            return c.toString();
        }

        function insertLegend() {

            if (options.legend.container != null) {
                $(options.legend.container).html("");
            } else {
                placeholder.find(".legend").remove();
            }

            if (!options.legend.show) {
                return;
            }

            var fragments = [], entries = [], rowStarted = false,
                lf = options.legend.labelFormatter, s, label;

            // Build a list of legend entries, with each having a label and a color

            for (var i = 0; i < series.length; ++i) {
                s = series[i];
                if (s.label) {
                    label = lf ? lf(s.label, s) : s.label;
                    if (label) {
                        entries.push({
                            label: label,
                            color: s.color
                        });
                    }
                }
            }

            // Sort the legend using either the default or a custom comparator

            if (options.legend.sorted) {
                if ($.isFunction(options.legend.sorted)) {
                    entries.sort(options.legend.sorted);
                } else if (options.legend.sorted == "reverse") {
                	entries.reverse();
                } else {
                    var ascending = options.legend.sorted != "descending";
                    entries.sort(function(a, b) {
                        return a.label == b.label ? 0 : (
                            (a.label < b.label) != ascending ? 1 : -1   // Logical XOR
                        );
                    });
                }
            }

            // Generate markup for the list of entries, in their final order

            for (var i = 0; i < entries.length; ++i) {

                var entry = entries[i];

                if (i % options.legend.noColumns == 0) {
                    if (rowStarted)
                        fragments.push('</tr>');
                    fragments.push('<tr>');
                    rowStarted = true;
                }

                fragments.push(
                    '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
                    '<td class="legendLabel">' + entry.label + '</td>'
                );
            }

            if (rowStarted)
                fragments.push('</tr>');

            if (fragments.length == 0)
                return;

            var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
            if (options.legend.container != null)
                $(options.legend.container).html(table);
            else {
                var pos = "",
                    p = options.legend.position,
                    m = options.legend.margin;
                if (m[0] == null)
                    m = [m, m];
                if (p.charAt(0) == "n")
                    pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
                else if (p.charAt(0) == "s")
                    pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
                if (p.charAt(1) == "e")
                    pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
                else if (p.charAt(1) == "w")
                    pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
                var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
                if (options.legend.backgroundOpacity != 0.0) {
                    // put in the transparent background
                    // separately to avoid blended labels and
                    // label boxes
                    var c = options.legend.backgroundColor;
                    if (c == null) {
                        c = options.grid.backgroundColor;
                        if (c && typeof c == "string")
                            c = $.color.parse(c);
                        else
                            c = $.color.extract(legend, 'background-color');
                        c.a = 1;
                        c = c.toString();
                    }
                    var div = legend.children();
                    $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
                }
            }
        }


        // interactive features

        var highlights = [],
            redrawTimeout = null;

        // returns the data item the mouse is over, or null if none is found
        function findNearbyItem(mouseX, mouseY, seriesFilter) {
            var maxDistance = options.grid.mouseActiveRadius,
                smallestDistance = maxDistance * maxDistance + 1,
                item = null, foundPoint = false, i, j, ps;

            for (i = series.length - 1; i >= 0; --i) {
                if (!seriesFilter(series[i]))
                    continue;

                var s = series[i],
                    axisx = s.xaxis,
                    axisy = s.yaxis,
                    points = s.datapoints.points,
                    mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
                    my = axisy.c2p(mouseY),
                    maxx = maxDistance / axisx.scale,
                    maxy = maxDistance / axisy.scale;

                ps = s.datapoints.pointsize;
                // with inverse transforms, we can't use the maxx/maxy
                // optimization, sadly
                if (axisx.options.inverseTransform)
                    maxx = Number.MAX_VALUE;
                if (axisy.options.inverseTransform)
                    maxy = Number.MAX_VALUE;

                if (s.lines.show || s.points.show) {
                    for (j = 0; j < points.length; j += ps) {
                        var x = points[j], y = points[j + 1];
                        if (x == null)
                            continue;

                        // For points and lines, the cursor must be within a
                        // certain distance to the data point
                        if (x - mx > maxx || x - mx < -maxx ||
                            y - my > maxy || y - my < -maxy)
                            continue;

                        // We have to calculate distances in pixels, not in
                        // data units, because the scales of the axes may be different
                        var dx = Math.abs(axisx.p2c(x) - mouseX),
                            dy = Math.abs(axisy.p2c(y) - mouseY),
                            dist = dx * dx + dy * dy; // we save the sqrt

                        // use <= to ensure last point takes precedence
                        // (last generally means on top of)
                        if (dist < smallestDistance) {
                            smallestDistance = dist;
                            item = [i, j / ps];
                        }
                    }
                }

                if (s.bars.show && !item) { // no other point can be nearby

                    var barLeft, barRight;

                    switch (s.bars.align) {
                        case "left":
                            barLeft = 0;
                            break;
                        case "right":
                            barLeft = -s.bars.barWidth;
                            break;
                        default:
                            barLeft = -s.bars.barWidth / 2;
                    }

                    barRight = barLeft + s.bars.barWidth;

                    for (j = 0; j < points.length; j += ps) {
                        var x = points[j], y = points[j + 1], b = points[j + 2];
                        if (x == null)
                            continue;

                        // for a bar graph, the cursor must be inside the bar
                        if (series[i].bars.horizontal ?
                            (mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
                             my >= y + barLeft && my <= y + barRight) :
                            (mx >= x + barLeft && mx <= x + barRight &&
                             my >= Math.min(b, y) && my <= Math.max(b, y)))
                                item = [i, j / ps];
                    }
                }
            }

            if (item) {
                i = item[0];
                j = item[1];
                ps = series[i].datapoints.pointsize;

                return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
                         dataIndex: j,
                         series: series[i],
                         seriesIndex: i };
            }

            return null;
        }

        function onMouseMove(e) {
            if (options.grid.hoverable)
                triggerClickHoverEvent("plothover", e,
                                       function (s) { return s["hoverable"] != false; });
        }

        function onMouseLeave(e) {
            if (options.grid.hoverable)
                triggerClickHoverEvent("plothover", e,
                                       function (s) { return false; });
        }

        function onClick(e) {
          if (plot.isSelecting) {
            return;
          }

          triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; });
        }

        // trigger click or hover event (they send the same parameters
        // so we share their code)
        function triggerClickHoverEvent(eventname, event, seriesFilter) {
            var offset = eventHolder.offset(),
                canvasX = event.pageX - offset.left - plotOffset.left,
                canvasY = event.pageY - offset.top - plotOffset.top,
            pos = canvasToAxisCoords({ left: canvasX, top: canvasY });

            pos.pageX = event.pageX;
            pos.pageY = event.pageY;

            // Add ctrlKey and metaKey to event
            pos.ctrlKey = event.ctrlKey;
            pos.metaKey = event.metaKey;

            var item = findNearbyItem(canvasX, canvasY, seriesFilter);

            if (item) {
                // fill in mouse pos for any listeners out there
                item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
                item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
            }

            if (options.grid.autoHighlight) {
                // clear auto-highlights
                for (var i = 0; i < highlights.length; ++i) {
                    var h = highlights[i];
                    if (h.auto == eventname &&
                        !(item && h.series == item.series &&
                          h.point[0] == item.datapoint[0] &&
                          h.point[1] == item.datapoint[1]))
                        unhighlight(h.series, h.point);
                }

                if (item)
                    highlight(item.series, item.datapoint, eventname);
            }

            placeholder.trigger(eventname, [ pos, item ]);
        }

        function triggerRedrawOverlay() {
            var t = options.interaction.redrawOverlayInterval;
            if (t == -1) {      // skip event queue
                drawOverlay();
                return;
            }

            if (!redrawTimeout)
                redrawTimeout = setTimeout(drawOverlay, t);
        }

        function drawOverlay() {
            redrawTimeout = null;

            // draw highlights
            octx.save();
            overlay.clear();
            octx.translate(plotOffset.left, plotOffset.top);

            var i, hi;
            for (i = 0; i < highlights.length; ++i) {
                hi = highlights[i];

                if (hi.series.bars.show)
                    drawBarHighlight(hi.series, hi.point);
                else
                    drawPointHighlight(hi.series, hi.point);
            }
            octx.restore();

            executeHooks(hooks.drawOverlay, [octx]);
        }

        function highlight(s, point, auto) {
            if (typeof s == "number")
                s = series[s];

            if (typeof point == "number") {
                var ps = s.datapoints.pointsize;
                point = s.datapoints.points.slice(ps * point, ps * (point + 1));
            }

            var i = indexOfHighlight(s, point);
            if (i == -1) {
                highlights.push({ series: s, point: point, auto: auto });

                triggerRedrawOverlay();
            }
            else if (!auto)
                highlights[i].auto = false;
        }

        function unhighlight(s, point) {
            if (s == null && point == null) {
                highlights = [];
                triggerRedrawOverlay();
                return;
            }

            if (typeof s == "number")
                s = series[s];

            if (typeof point == "number") {
                var ps = s.datapoints.pointsize;
                point = s.datapoints.points.slice(ps * point, ps * (point + 1));
            }

            var i = indexOfHighlight(s, point);
            if (i != -1) {
                highlights.splice(i, 1);

                triggerRedrawOverlay();
            }
        }

        function indexOfHighlight(s, p) {
            for (var i = 0; i < highlights.length; ++i) {
                var h = highlights[i];
                if (h.series == s && h.point[0] == p[0]
                    && h.point[1] == p[1])
                    return i;
            }
            return -1;
        }

        function drawPointHighlight(series, point) {
            var x = point[0], y = point[1],
                axisx = series.xaxis, axisy = series.yaxis,
                highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();

            if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
                return;

            var pointRadius = series.points.radius + series.points.lineWidth / 2;
            octx.lineWidth = pointRadius;
            octx.strokeStyle = highlightColor;
            var radius = 1.5 * pointRadius;
            x = axisx.p2c(x);
            y = axisy.p2c(y);

            octx.beginPath();
            if (series.points.symbol == "circle")
                octx.arc(x, y, radius, 0, 2 * Math.PI, false);
            else
                series.points.symbol(octx, x, y, radius, false);
            octx.closePath();
            octx.stroke();
        }

        function drawBarHighlight(series, point) {
            var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
                fillStyle = highlightColor,
                barLeft;

            switch (series.bars.align) {
                case "left":
                    barLeft = 0;
                    break;
                case "right":
                    barLeft = -series.bars.barWidth;
                    break;
                default:
                    barLeft = -series.bars.barWidth / 2;
            }

            octx.lineWidth = series.bars.lineWidth;
            octx.strokeStyle = highlightColor;

            drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
                    function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
        }

        function getColorOrGradient(spec, bottom, top, defaultColor) {
            if (typeof spec == "string")
                return spec;
            else {
                // assume this is a gradient spec; IE currently only
                // supports a simple vertical gradient properly, so that's
                // what we support too
                var gradient = ctx.createLinearGradient(0, top, 0, bottom);

                for (var i = 0, l = spec.colors.length; i < l; ++i) {
                    var c = spec.colors[i];
                    if (typeof c != "string") {
                        var co = $.color.parse(defaultColor);
                        if (c.brightness != null)
                            co = co.scale('rgb', c.brightness);
                        if (c.opacity != null)
                            co.a *= c.opacity;
                        c = co.toString();
                    }
                    gradient.addColorStop(i / (l - 1), c);
                }

                return gradient;
            }
        }
    }

    // Add the plot function to the top level of the jQuery object

    $.plot = function(placeholder, data, options) {
        //var t0 = new Date();
        var plot = new Plot($(placeholder), data, options, $.plot.plugins);
        //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
        return plot;
    };

    $.plot.version = "0.8.3";

    $.plot.plugins = [];

    // Also add the plot function as a chainable property

    $.fn.plot = function(data, options) {
        return this.each(function() {
            $.plot(this, data, options);
        });
    };

    // round to nearby lower multiple of base
    function floorInBase(n, base) {
        return base * Math.floor(n / base);
    }

})(jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.pie.js":
/*!***********************************************!*\
  !*** ./public/vendor/flot/jquery.flot.pie.js ***!
  \***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {



/***/ }),

/***/ "./public/vendor/flot/jquery.flot.selection.js":
/*!*****************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.selection.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* Flot plugin for selecting regions of a plot.

Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.

The plugin supports these options:

selection: {
	mode: null or "x" or "y" or "xy",
	color: color,
	shape: "round" or "miter" or "bevel",
	minSize: number of pixels
}

Selection support is enabled by setting the mode to one of "x", "y" or "xy".
In "x" mode, the user will only be able to specify the x range, similarly for
"y" mode. For "xy", the selection becomes a rectangle where both ranges can be
specified. "color" is color of the selection (if you need to change the color
later on, you can get to it with plot.getOptions().selection.color). "shape"
is the shape of the corners of the selection.

"minSize" is the minimum size a selection can be in pixels. This value can
be customized to determine the smallest size a selection can be and still
have the selection rectangle be displayed. When customizing this value, the
fact that it refers to pixels, not axis units must be taken into account.
Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
minute, setting "minSize" to 1 will not make the minimum selection size 1
minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
"plotunselected" events from being fired when the user clicks the mouse without
dragging.

When selection support is enabled, a "plotselected" event will be emitted on
the DOM element you passed into the plot function. The event handler gets a
parameter with the ranges selected on the axes, like this:

	placeholder.bind( "plotselected", function( event, ranges ) {
		alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
		// similar for yaxis - with multiple axes, the extra ones are in
		// x2axis, x3axis, ...
	});

The "plotselected" event is only fired when the user has finished making the
selection. A "plotselecting" event is fired during the process with the same
parameters as the "plotselected" event, in case you want to know what's
happening while it's happening,

A "plotunselected" event with no arguments is emitted when the user clicks the
mouse to remove the selection. As stated above, setting "minSize" to 0 will
destroy this behavior.

The plugin allso adds the following methods to the plot object:

- setSelection( ranges, preventEvent )

  Set the selection rectangle. The passed in ranges is on the same form as
  returned in the "plotselected" event. If the selection mode is "x", you
  should put in either an xaxis range, if the mode is "y" you need to put in
  an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
  this:

	setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });

  setSelection will trigger the "plotselected" event when called. If you don't
  want that to happen, e.g. if you're inside a "plotselected" handler, pass
  true as the second parameter. If you are using multiple axes, you can
  specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
  xaxis, the plugin picks the first one it sees.

- clearSelection( preventEvent )

  Clear the selection rectangle. Pass in true to avoid getting a
  "plotunselected" event.

- getSelection()

  Returns the current selection in the same format as the "plotselected"
  event. If there's currently no selection, the function returns null.

*/

(function ($) {
    function init(plot) {
        var selection = {
                first: { x: -1, y: -1}, second: { x: -1, y: -1},
                show: false,
                active: false
            };

        // FIXME: The drag handling implemented here should be
        // abstracted out, there's some similar code from a library in
        // the navigation plugin, this should be massaged a bit to fit
        // the Flot cases here better and reused. Doing this would
        // make this plugin much slimmer.
        var savedhandlers = {};

        var mouseUpHandler = null;

        function onMouseMove(e) {
            if (selection.active) {
                updateSelection(e);

                plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
            }
        }

        function onMouseDown(e) {
            if (e.which != 1)  // only accept left-click
                return;

            // cancel out any text selections
            document.body.focus();

            // prevent text selection and drag in old-school browsers
            if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
                savedhandlers.onselectstart = document.onselectstart;
                document.onselectstart = function () { return false; };
            }
            if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
                savedhandlers.ondrag = document.ondrag;
                document.ondrag = function () { return false; };
            }

            setSelectionPos(selection.first, e);

            selection.active = true;

            // this is a bit silly, but we have to use a closure to be
            // able to whack the same handler again
            mouseUpHandler = function (e) { onMouseUp(e); };

            $(document).one("mouseup", mouseUpHandler);
        }

        function onMouseUp(e) {
            mouseUpHandler = null;

            // revert drag stuff for old-school browsers
            if (document.onselectstart !== undefined)
                document.onselectstart = savedhandlers.onselectstart;
            if (document.ondrag !== undefined)
                document.ondrag = savedhandlers.ondrag;

            // no more dragging
            selection.active = false;
            updateSelection(e);

            if (selectionIsSane())
                triggerSelectedEvent(e);
            else {
                // this counts as a clear
                plot.getPlaceholder().trigger("plotunselected", [ ]);
                plot.getPlaceholder().trigger("plotselecting", [ null ]);
            }

            setTimeout(function() {
              plot.isSelecting = false;
            }, 10);

            return false;
        }

        function getSelection() {
            if (!selectionIsSane())
                return null;

            if (!selection.show) return null;

            var r = {}, c1 = selection.first, c2 = selection.second;
            var axes = plot.getAxes();
            // look if no axis is used
            var noAxisInUse = true;
            $.each(axes, function (name, axis) {
              if (axis.used) {
                anyUsed = false;
              }
            })

            $.each(axes, function (name, axis) {
                if (axis.used || noAxisInUse) {
                    var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
                    r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
                }
            });
            return r;
        }

        function triggerSelectedEvent(event) {
            var r = getSelection();

            // Add ctrlKey and metaKey to event
            r.ctrlKey = event.ctrlKey;
            r.metaKey = event.metaKey;

            plot.getPlaceholder().trigger("plotselected", [ r ]);

            // backwards-compat stuff, to be removed in future
            if (r.xaxis && r.yaxis)
                plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
        }

        function clamp(min, value, max) {
            return value < min ? min: (value > max ? max: value);
        }

        function setSelectionPos(pos, e) {
            var o = plot.getOptions();
            var offset = plot.getPlaceholder().offset();
            var plotOffset = plot.getPlotOffset();
            pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
            pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());

            if (o.selection.mode == "y")
                pos.x = pos == selection.first ? 0 : plot.width();

            if (o.selection.mode == "x")
                pos.y = pos == selection.first ? 0 : plot.height();
        }

        function updateSelection(pos) {
            if (pos.pageX == null)
                return;

            setSelectionPos(selection.second, pos);
            if (selectionIsSane()) {
                plot.isSelecting = true;
                selection.show = true;
                plot.triggerRedrawOverlay();
            }
            else
                clearSelection(true);
        }

        function clearSelection(preventEvent) {
            if (selection.show) {
                selection.show = false;
                plot.triggerRedrawOverlay();
                if (!preventEvent)
                    plot.getPlaceholder().trigger("plotunselected", [ ]);
            }
        }

        // function taken from markings support in Flot
        function extractRange(ranges, coord) {
            var axis, from, to, key, axes = plot.getAxes();

            for (var k in axes) {
                axis = axes[k];
                if (axis.direction == coord) {
                    key = coord + axis.n + "axis";
                    if (!ranges[key] && axis.n == 1)
                        key = coord + "axis"; // support x1axis as xaxis
                    if (ranges[key]) {
                        from = ranges[key].from;
                        to = ranges[key].to;
                        break;
                    }
                }
            }

            // backwards-compat stuff - to be removed in future
            if (!ranges[key]) {
                axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
                from = ranges[coord + "1"];
                to = ranges[coord + "2"];
            }

            // auto-reverse as an added bonus
            if (from != null && to != null && from > to) {
                var tmp = from;
                from = to;
                to = tmp;
            }

            return { from: from, to: to, axis: axis };
        }

        function setSelection(ranges, preventEvent) {
            var axis, range, o = plot.getOptions();

            if (o.selection.mode == "y") {
                selection.first.x = 0;
                selection.second.x = plot.width();
            }
            else {
                range = extractRange(ranges, "x");

                selection.first.x = range.axis.p2c(range.from);
                selection.second.x = range.axis.p2c(range.to);
            }

            if (o.selection.mode == "x") {
                selection.first.y = 0;
                selection.second.y = plot.height();
            }
            else {
                range = extractRange(ranges, "y");

                selection.first.y = range.axis.p2c(range.from);
                selection.second.y = range.axis.p2c(range.to);
            }

            selection.show = true;
            plot.triggerRedrawOverlay();
            if (!preventEvent && selectionIsSane())
                triggerSelectedEvent();
        }

        function selectionIsSane() {
            var minSize = plot.getOptions().selection.minSize;
            return Math.abs(selection.second.x - selection.first.x) >= minSize &&
                Math.abs(selection.second.y - selection.first.y) >= minSize;
        }

        plot.clearSelection = clearSelection;
        plot.setSelection = setSelection;
        plot.getSelection = getSelection;

        plot.hooks.bindEvents.push(function(plot, eventHolder) {
            var o = plot.getOptions();
            if (o.selection.mode != null) {
                eventHolder.mousemove(onMouseMove);
                eventHolder.mousedown(onMouseDown);
            }
        });


        plot.hooks.drawOverlay.push(function (plot, ctx) {
            // draw selection
            if (selection.show && selectionIsSane()) {
                var plotOffset = plot.getPlotOffset();
                var o = plot.getOptions();

                ctx.save();
                ctx.translate(plotOffset.left, plotOffset.top);

                var c = $.color.parse(o.selection.color);

                ctx.strokeStyle = c.scale('a', 0.8).toString();
                ctx.lineWidth = 1;
                ctx.lineJoin = o.selection.shape;
                ctx.fillStyle = c.scale('a', 0.4).toString();

                var x = Math.min(selection.first.x, selection.second.x) + 0.5,
                    y = Math.min(selection.first.y, selection.second.y) + 0.5,
                    w = Math.abs(selection.second.x - selection.first.x) - 1,
                    h = Math.abs(selection.second.y - selection.first.y) - 1;

                ctx.fillRect(x, y, w, h);
                ctx.strokeRect(x, y, w, h);

                ctx.restore();
            }
        });

        plot.hooks.shutdown.push(function (plot, eventHolder) {
            eventHolder.unbind("mousemove", onMouseMove);
            eventHolder.unbind("mousedown", onMouseDown);

            if (mouseUpHandler)
                $(document).unbind("mouseup", mouseUpHandler);
        });

    }

    $.plot.plugins.push({
        init: init,
        options: {
            selection: {
                mode: null, // one of null, "x", "y" or "xy"
                color: "#e8cfac",
                shape: "round", // one of "round", "miter", or "bevel"
                minSize: 5 // minimum number of pixels
            }
        },
        name: 'selection',
        version: '1.1'
    });
})(jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.stack.js":
/*!*************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.stack.js ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* Flot plugin for stacking data sets rather than overlyaing them.

Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.

The plugin assumes the data is sorted on x (or y if stacking horizontally).
For line charts, it is assumed that if a line has an undefined gap (from a
null point), then the line above it should have the same gap - insert zeros
instead of "null" if you want another behaviour. This also holds for the start
and end of the chart. Note that stacking a mix of positive and negative values
in most instances doesn't make sense (so it looks weird).

Two or more series are stacked when their "stack" attribute is set to the same
key (which can be any number or string or just "true"). To specify the default
stack, you can set the stack option like this:

    series: {
        stack: null/false, true, or a key (number/string)
    }

You can also specify it for a single series, like this:

    $.plot( $("#placeholder"), [{
        data: [ ... ],
        stack: true
    }])

The stacking order is determined by the order of the data series in the array
(later series end up on top of the previous).

Internally, the plugin modifies the datapoints in each series, adding an
offset to the y value. For line series, extra data points are inserted through
interpolation. If there's a second y value, it's also adjusted (e.g for bar
charts or filled areas).

*/

(function ($) {
    var options = {
        series: { stack: null } // or number/string
    };

    function init(plot) {
        function findMatchingSeries(s, allseries) {
            var res = null;
            for (var i = 0; i < allseries.length; ++i) {
                if (s == allseries[i])
                    break;

                if (allseries[i].stack == s.stack)
                    res = allseries[i];
            }

            return res;
        }

        function stackData(plot, s, datapoints) {
            if (s.stack == null || s.stack === false)
                return;

            var other = findMatchingSeries(s, plot.getData());
            if (!other)
                return;

            var ps = datapoints.pointsize,
                points = datapoints.points,
                otherps = other.datapoints.pointsize,
                otherpoints = other.datapoints.points,
                newpoints = [],
                px, py, intery, qx, qy, bottom,
                withlines = s.lines.show,
                horizontal = s.bars.horizontal,
                withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y),
                withsteps = withlines && s.lines.steps,
                keyOffset = horizontal ? 1 : 0,
                accumulateOffset = horizontal ? 0 : 1,
                i = 0, j = 0, l, m;

            while (true) {
                if (i >= points.length && j >= otherpoints.length)
                    break;

                l = newpoints.length;

                if (i < points.length && points[i] == null) {
                    // copy gaps
                    for (m = 0; m < ps; ++m)
                        newpoints.push(points[i + m]);
                    i += ps;
                }
                else if (i >= points.length) {
                    // take the remaining points from the previous series
                    for (m = 0; m < ps; ++m)
                        newpoints.push(otherpoints[j + m]);
                    if (withbottom)
                        newpoints[l + 2] = otherpoints[j + accumulateOffset];
                    j += otherps;
                }
                else if (j >= otherpoints.length) {
                    // take the remaining points from the current series
                    for (m = 0; m < ps; ++m)
                        newpoints.push(points[i + m]);
                    i += ps;
                }
                else if (j < otherpoints.length && otherpoints[j] == null) {
                    // ignore point
                    j += otherps;
                }
                else {
                    // cases where we actually got two points
                    px = points[i + keyOffset];
                    py = points[i + accumulateOffset];
                    qx = otherpoints[j + keyOffset];
                    qy = otherpoints[j + accumulateOffset];
                    bottom = 0;

                    if (px == qx) {
                        for (m = 0; m < ps; ++m)
                            newpoints.push(points[i + m]);

                        newpoints[l + accumulateOffset] += qy;
                        bottom = qy;

                        i += ps;
                        j += otherps;
                    }
                    else if (px > qx) {
                        // take the point from the previous series so that next series will correctly stack
                        if (i == 0) {
                            for (m = 0; m < ps; ++m)
                                newpoints.push(otherpoints[j + m]);
                            bottom = qy;
                        }
                        // we got past point below, might need to
                        // insert interpolated extra point
                        if (i > 0 && points[i - ps] != null) {
                            intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px);
                            newpoints.push(qx);
                            newpoints.push(intery + qy);
                            for (m = 2; m < ps; ++m)
                                newpoints.push(points[i + m]);
                            bottom = qy;
                        }

                        j += otherps;
                    }
                    else { // px < qx
                        for (m = 0; m < ps; ++m)
                            newpoints.push(points[i + m]);

                        // we might be able to interpolate a point below,
                        // this can give us a better y
                        if (j > 0 && otherpoints[j - otherps] != null)
                            bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx);

                        newpoints[l + accumulateOffset] += bottom;

                        i += ps;
                    }

                    fromgap = false;

                    if (l != newpoints.length && withbottom)
                        newpoints[l + 2] = bottom;
                }

                // maintain the line steps invariant
                if (withsteps && l != newpoints.length && l > 0
                    && newpoints[l] != null
                    && newpoints[l] != newpoints[l - ps]
                    && newpoints[l + 1] != newpoints[l - ps + 1]) {
                    for (m = 0; m < ps; ++m)
                        newpoints[l + ps + m] = newpoints[l + m];
                    newpoints[l + 1] = newpoints[l - ps + 1];
                }
            }

            datapoints.points = newpoints;
        }

        plot.hooks.processDatapoints.push(stackData);
    }

    $.plot.plugins.push({
        init: init,
        options: options,
        name: 'stack',
        version: '1.2'
    });
})(jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.stackpercent.js":
/*!********************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.stackpercent.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

(function ($) {
    var options = {
        series: {
            stackpercent: null
        } // or number/string
    };

    function init(plot) {

        // will be built up dynamically as a hash from x-value, or y-value if horizontal
        var stackBases = {};
        var processed = false;
        var stackSums = {};

        //set percentage for stacked chart
        function processRawData(plot, series, data, datapoints) {
            if (!processed) {
                processed = true;
                stackSums = getStackSums(plot.getData());
            }
			if (series.stackpercent == true) {
				var num = data.length;
				series.percents = [];
				var key_idx = 0;
				var value_idx = 1;
				if (series.bars && series.bars.horizontal && series.bars.horizontal === true) {
					key_idx = 1;
					value_idx = 0;
				}
				for (var j = 0; j < num; j++) {
					var sum = stackSums[data[j][key_idx] + ""];
					if (sum > 0) {
						series.percents.push(data[j][value_idx] * 100 / sum);
					} else {
						series.percents.push(0);
					}
				}
			}
        }

        //calculate summary
        function getStackSums(_data) {
            var data_len = _data.length;
            var sums = {};
            if (data_len > 0) {
                //caculate summary
                for (var i = 0; i < data_len; i++) {
                    if (_data[i].stackpercent) {
						var key_idx = 0;
						var value_idx = 1;
						if (_data[i].bars && _data[i].bars.horizontal && _data[i].bars.horizontal === true) {
							key_idx = 1;
							value_idx = 0;
						}
                        var num = _data[i].data.length;
                        for (var j = 0; j < num; j++) {
                            var value = 0;
                            if (_data[i].data[j][1] != null) {
                                value = _data[i].data[j][value_idx];
                            }
                            if (sums[_data[i].data[j][key_idx] + ""]) {
                                sums[_data[i].data[j][key_idx] + ""] += value;
                            } else {
                                sums[_data[i].data[j][key_idx] + ""] = value;
                            }

                        }
                    }
                }
            }
            return sums;
        }

        function stackData(plot, s, datapoints) {
            if (!s.stackpercent) return;
            if (!processed) {
                stackSums = getStackSums(plot.getData());
            }
            var newPoints = [];


			var key_idx = 0;
			var value_idx = 1;
			if (s.bars && s.bars.horizontal && s.bars.horizontal === true) {
				key_idx = 1;
				value_idx = 0;
			}

			for (var i = 0; i < datapoints.points.length; i += 3) {
				// note that the values need to be turned into absolute y-values.
				// in other words, if you were to stack (x, y1), (x, y2), and (x, y3),
				// (each from different series, which is where stackBases comes in),
				// you'd want the new points to be (x, y1, 0), (x, y1+y2, y1), (x, y1+y2+y3, y1+y2)
				// generally, (x, thisValue + (base up to this point), + (base up to this point))
				if (!stackBases[datapoints.points[i + key_idx]]) {
					stackBases[datapoints.points[i + key_idx]] = 0;
				}
				newPoints[i + key_idx] = datapoints.points[i + key_idx];
				newPoints[i + value_idx] = datapoints.points[i + value_idx] + stackBases[datapoints.points[i + key_idx]];
				newPoints[i + 2] = stackBases[datapoints.points[i + key_idx]];
				stackBases[datapoints.points[i + key_idx]] += datapoints.points[i + value_idx];
				// change points to percentage values
				// you may need to set yaxis:{ max = 100 }
				if ( stackSums[newPoints[i+key_idx]+""] > 0 ){
					newPoints[i + value_idx] = newPoints[i + value_idx] * 100 / stackSums[newPoints[i + key_idx] + ""];
					newPoints[i + 2] = newPoints[i + 2] * 100 / stackSums[newPoints[i + key_idx] + ""];
				} else {
					newPoints[i + value_idx] = 0;
					newPoints[i + 2] = 0;
				}
			}

            datapoints.points = newPoints;
        }

		plot.hooks.processRawData.push(processRawData);
        plot.hooks.processDatapoints.push(stackData);
    }

    $.plot.plugins.push({
        init: init,
        options: options,
        name: 'stackpercent',
        version: '0.1'
    });
})(jQuery);


/***/ }),

/***/ "./public/vendor/flot/jquery.flot.time.js":
/*!************************************************!*\
  !*** ./public/vendor/flot/jquery.flot.time.js ***!
  \************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

/* Pretty handling of time axes.

Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.

Set axis.mode to "time" to enable. See the section "Time series data" in
API.txt for details.

*/

(function($) {

	var options = {
		xaxis: {
			timezone: null,		// "browser" for local to the client or timezone for timezone-js
			timeformat: null,	// format string to use
			twelveHourClock: false,	// 12 or 24 time in time mode
			monthNames: null	// list of names of months
		}
	};

	// round to nearby lower multiple of base

	function floorInBase(n, base) {
		return base * Math.floor(n / base);
	}

	// Returns a string with the date d formatted according to fmt.
	// A subset of the Open Group's strftime format is supported.

	function formatDate(d, fmt, monthNames, dayNames) {

		if (typeof d.strftime == "function") {
			return d.strftime(fmt);
		}

		var leftPad = function(n, pad) {
			n = "" + n;
			pad = "" + (pad == null ? "0" : pad);
			return n.length == 1 ? pad + n : n;
		};

		var r = [];
		var escape = false;
		var hours = d.getHours();
		var isAM = hours < 12;

		if (monthNames == null) {
			monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
		}

		if (dayNames == null) {
			dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
		}

		var hours12;

		if (hours > 12) {
			hours12 = hours - 12;
		} else if (hours == 0) {
			hours12 = 12;
		} else {
			hours12 = hours;
		}

		for (var i = 0; i < fmt.length; ++i) {

			var c = fmt.charAt(i);

			if (escape) {
				switch (c) {
					case 'a': c = "" + dayNames[d.getDay()]; break;
					case 'b': c = "" + monthNames[d.getMonth()]; break;
					case 'd': c = leftPad(d.getDate(), ""); break;
					case 'e': c = leftPad(d.getDate(), " "); break;
					case 'h':	// For back-compat with 0.7; remove in 1.0
					case 'H': c = leftPad(hours); break;
					case 'I': c = leftPad(hours12); break;
					case 'l': c = leftPad(hours12, " "); break;
					case 'm': c = leftPad(d.getMonth() + 1, ""); break;
					case 'M': c = leftPad(d.getMinutes()); break;
					// quarters not in Open Group's strftime specification
					case 'q':
						c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
					case 'S': c = leftPad(d.getSeconds()); break;
					case 'y': c = leftPad(d.getFullYear() % 100); break;
					case 'Y': c = "" + d.getFullYear(); break;
					case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
					case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
					case 'w': c = "" + d.getDay(); break;
				}
				r.push(c);
				escape = false;
			} else {
				if (c == "%") {
					escape = true;
				} else {
					r.push(c);
				}
			}
		}

		return r.join("");
	}

	// To have a consistent view of time-based data independent of which time
	// zone the client happens to be in we need a date-like object independent
	// of time zones.  This is done through a wrapper that only calls the UTC
	// versions of the accessor methods.

	function makeUtcWrapper(d) {

		function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
			sourceObj[sourceMethod] = function() {
				return targetObj[targetMethod].apply(targetObj, arguments);
			};
		};

		var utc = {
			date: d
		};

		// support strftime, if found

		if (d.strftime != undefined) {
			addProxyMethod(utc, "strftime", d, "strftime");
		}

		addProxyMethod(utc, "getTime", d, "getTime");
		addProxyMethod(utc, "setTime", d, "setTime");

		var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];

		for (var p = 0; p < props.length; p++) {
			addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
			addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
		}

		return utc;
	};

	// select time zone strategy.  This returns a date-like object tied to the
	// desired timezone

	function dateGenerator(ts, opts) {
		if (opts.timezone == "browser") {
			return new Date(ts);
		} else if (!opts.timezone || opts.timezone == "utc") {
			return makeUtcWrapper(new Date(ts));
		} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
			var d = new timezoneJS.Date();
			// timezone-js is fickle, so be sure to set the time zone before
			// setting the time.
			d.setTimezone(opts.timezone);
			d.setTime(ts);
			return d;
		} else {
			return makeUtcWrapper(new Date(ts));
		}
	}

	// map of app. size of time units in milliseconds

	var timeUnitSize = {
		"second": 1000,
		"minute": 60 * 1000,
		"hour": 60 * 60 * 1000,
		"day": 24 * 60 * 60 * 1000,
		"month": 30 * 24 * 60 * 60 * 1000,
		"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
		"year": 365.2425 * 24 * 60 * 60 * 1000
	};

	// the allowed tick sizes, after 1 year we use
	// an integer algorithm

	var baseSpec = [
		[1, "second"], [2, "second"], [5, "second"], [10, "second"],
		[30, "second"],
		[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
		[30, "minute"],
		[1, "hour"], [2, "hour"], [4, "hour"],
		[8, "hour"], [12, "hour"],
		[1, "day"], [2, "day"], [3, "day"],
		[0.25, "month"], [0.5, "month"], [1, "month"],
		[2, "month"]
	];

	// we don't know which variant(s) we'll need yet, but generating both is
	// cheap

	var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
		[1, "year"]]);
	var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
		[1, "year"]]);

	function init(plot) {
		plot.hooks.processOptions.push(function (plot, options) {
			$.each(plot.getAxes(), function(axisName, axis) {

				var opts = axis.options;

				if (opts.mode == "time") {
					axis.tickGenerator = function(axis) {

						var ticks = [];
						var d = dateGenerator(axis.min, opts);
						var minSize = 0;

						// make quarter use a possibility if quarters are
						// mentioned in either of these options

						var spec = (opts.tickSize && opts.tickSize[1] ===
							"quarter") ||
							(opts.minTickSize && opts.minTickSize[1] ===
							"quarter") ? specQuarters : specMonths;

						if (opts.minTickSize != null) {
							if (typeof opts.tickSize == "number") {
								minSize = opts.tickSize;
							} else {
								minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
							}
						}

						for (var i = 0; i < spec.length - 1; ++i) {
							if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
											  + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
								&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
								break;
							}
						}

						var size = spec[i][0];
						var unit = spec[i][1];

						// special-case the possibility of several years

						if (unit == "year") {

							// if given a minTickSize in years, just use it,
							// ensuring that it's an integer

							if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
								size = Math.floor(opts.minTickSize[0]);
							} else {

								var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
								var norm = (axis.delta / timeUnitSize.year) / magn;

								if (norm < 1.5) {
									size = 1;
								} else if (norm < 3) {
									size = 2;
								} else if (norm < 7.5) {
									size = 5;
								} else {
									size = 10;
								}

								size *= magn;
							}

							// minimum size for years is 1

							if (size < 1) {
								size = 1;
							}
						}

						axis.tickSize = opts.tickSize || [size, unit];
						var tickSize = axis.tickSize[0];
						unit = axis.tickSize[1];

						var step = tickSize * timeUnitSize[unit];

						if (unit == "second") {
							d.setSeconds(floorInBase(d.getSeconds(), tickSize));
						} else if (unit == "minute") {
							d.setMinutes(floorInBase(d.getMinutes(), tickSize));
						} else if (unit == "hour") {
							d.setHours(floorInBase(d.getHours(), tickSize));
						} else if (unit == "month") {
							d.setMonth(floorInBase(d.getMonth(), tickSize));
						} else if (unit == "quarter") {
							d.setMonth(3 * floorInBase(d.getMonth() / 3,
								tickSize));
						} else if (unit == "year") {
							d.setFullYear(floorInBase(d.getFullYear(), tickSize));
						}

						// reset smaller components

						d.setMilliseconds(0);

						if (step >= timeUnitSize.minute) {
							d.setSeconds(0);
						}
						if (step >= timeUnitSize.hour) {
							d.setMinutes(0);
						}
						if (step >= timeUnitSize.day) {
							d.setHours(0);
						}
						if (step >= timeUnitSize.day * 4) {
							d.setDate(1);
						}
						if (step >= timeUnitSize.month * 2) {
							d.setMonth(floorInBase(d.getMonth(), 3));
						}
						if (step >= timeUnitSize.quarter * 2) {
							d.setMonth(floorInBase(d.getMonth(), 6));
						}
						if (step >= timeUnitSize.year) {
							d.setMonth(0);
						}

						var carry = 0;
						var v = Number.NaN;
						var prev;

						do {

							prev = v;
							v = d.getTime();
							ticks.push(v);

							if (unit == "month" || unit == "quarter") {
								if (tickSize < 1) {

									// a bit complicated - we'll divide the
									// month/quarter up but we need to take
									// care of fractions so we don't end up in
									// the middle of a day

									d.setDate(1);
									var start = d.getTime();
									d.setMonth(d.getMonth() +
										(unit == "quarter" ? 3 : 1));
									var end = d.getTime();
									d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
									carry = d.getHours();
									d.setHours(0);
								} else {
									d.setMonth(d.getMonth() +
										tickSize * (unit == "quarter" ? 3 : 1));
								}
							} else if (unit == "year") {
								d.setFullYear(d.getFullYear() + tickSize);
							} else {
								d.setTime(v + step);
							}
						} while (v < axis.max && v != prev);

						return ticks;
					};

					axis.tickFormatter = function (v, axis) {

						var d = dateGenerator(v, axis.options);

						// first check global format

						if (opts.timeformat != null) {
							return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
						}

						// possibly use quarters if quarters are mentioned in
						// any of these places

						var useQuarters = (axis.options.tickSize &&
								axis.options.tickSize[1] == "quarter") ||
							(axis.options.minTickSize &&
								axis.options.minTickSize[1] == "quarter");

						var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
						var span = axis.max - axis.min;
						var suffix = (opts.twelveHourClock) ? " %p" : "";
						var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
						var fmt;

						if (t < timeUnitSize.minute) {
							fmt = hourCode + ":%M:%S" + suffix;
						} else if (t < timeUnitSize.day) {
							if (span < 2 * timeUnitSize.day) {
								fmt = hourCode + ":%M" + suffix;
							} else {
								fmt = "%b %d " + hourCode + ":%M" + suffix;
							}
						} else if (t < timeUnitSize.month) {
							fmt = "%b %d";
						} else if ((useQuarters && t < timeUnitSize.quarter) ||
							(!useQuarters && t < timeUnitSize.year)) {
							if (span < timeUnitSize.year) {
								fmt = "%b";
							} else {
								fmt = "%b %Y";
							}
						} else if (useQuarters && t < timeUnitSize.year) {
							if (span < timeUnitSize.year) {
								fmt = "Q%q";
							} else {
								fmt = "Q%q %Y";
							}
						} else {
							fmt = "%Y";
						}

						var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);

						return rt;
					};
				}
			});
		});
	}

	$.plot.plugins.push({
		init: init,
		options: options,
		name: 'time',
		version: '1.0'
	});

	// Time-axis support used to be in Flot core, which exposed the
	// formatDate function on the plot object.  Various plugins depend
	// on the function, so we need to re-expose it here.

	$.plot.formatDate = formatDate;

})(jQuery);


/***/ }),

/***/ "./public/vendor/tagsinput/bootstrap-tagsinput.js":
/*!********************************************************!*\
  !*** ./public/vendor/tagsinput/bootstrap-tagsinput.js ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

(function ($) {
  "use strict";

  var defaultOptions = {
    tagClass: function(item) {
      return 'label label-info';
    },
    itemValue: function(item) {
      return item ? item.toString() : item;
    },
    itemText: function(item) {
      return this.itemValue(item);
    },
    freeInput: true,
    maxTags: undefined,
    confirmKeys: [13],
    onTagExists: function(item, $tag) {
      $tag.hide().fadeIn();
    }
  };

  /**
   * Constructor function
   */
  function TagsInput(element, options) {
    this.itemsArray = [];

    this.$element = $(element);
    this.$element.hide();

    this.widthClass = options.widthClass || 'width-9';
    this.isSelect = (element.tagName === 'SELECT');
    this.multiple = (this.isSelect && element.hasAttribute('multiple'));
    this.objectItems = options && options.itemValue;
    this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';

    this.$container = $('<div class="bootstrap-tagsinput"></div>');
    this.$input = $('<input class="gf-form-input ' + this.widthClass + '" type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);

    this.$element.after(this.$container);

    this.build(options);
  }

  TagsInput.prototype = {
    constructor: TagsInput,

    /**
     * Adds the given item as a new tag. Pass true to dontPushVal to prevent
     * updating the elements val()
     */
    add: function(item, dontPushVal) {
      var self = this;

      if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
        return;

      // Ignore falsey values, except false
      if (item !== false && !item)
        return;

      // Throw an error when trying to add an object while the itemValue option was not set
      if (typeof item === "object" && !self.objectItems)
        throw("Can't add objects when itemValue option is not set");

      // Ignore strings only containg whitespace
      if (item.toString().match(/^\s*$/))
        return;

      // If SELECT but not multiple, remove current tag
      if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
        self.remove(self.itemsArray[0]);

      if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
        var items = item.split(',');
        if (items.length > 1) {
          for (var i = 0; i < items.length; i++) {
            this.add(items[i], true);
          }

          if (!dontPushVal)
            self.pushVal();
          return;
        }
      }

      var itemValue = self.options.itemValue(item),
          itemText = self.options.itemText(item),
          tagClass = self.options.tagClass(item);

      // Ignore items allready added
      var existing = $.grep(self.itemsArray, function(item) { return self.options.itemValue(item) === itemValue; } )[0];
      if (existing) {
        // Invoke onTagExists
        if (self.options.onTagExists) {
          var $existingTag = $(".tag", self.$container).filter(function() { return $(this).data("item") === existing; });
          self.options.onTagExists(item, $existingTag);
        }
        return;
      }

      // register item in internal array and map
      self.itemsArray.push(item);

      // add a tag element
      var $tag = $('<span class="tag ' + htmlEncode(tagClass) + '">' + htmlEncode(itemText) + '<span data-role="remove"></span></span>');
      $tag.data('item', item);
      self.findInputWrapper().before($tag);
      $tag.after(' ');

      // add <option /> if item represents a value not present in one of the <select />'s options
      if (self.isSelect && !$('option[value="' + escape(itemValue) + '"]',self.$element)[0]) {
        var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
        $option.data('item', item);
        $option.attr('value', itemValue);
        self.$element.append($option);
      }

      if (!dontPushVal)
        self.pushVal();

      // Add class when reached maxTags
      if (self.options.maxTags === self.itemsArray.length)
        self.$container.addClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemAdded', { item: item }));
    },

    /**
     * Removes the given item. Pass true to dontPushVal to prevent updating the
     * elements val()
     */
    remove: function(item, dontPushVal) {
      var self = this;

      if (self.objectItems) {
        if (typeof item === "object")
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  self.options.itemValue(item); } )[0];
        else
          item = $.grep(self.itemsArray, function(other) { return self.options.itemValue(other) ==  item; } )[0];
      }

      if (item) {
        $('.tag', self.$container).filter(function() { return $(this).data('item') === item; }).remove();
        $('option', self.$element).filter(function() { return $(this).data('item') === item; }).remove();
        self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
      }

      if (!dontPushVal)
        self.pushVal();

      // Remove class when reached maxTags
      if (self.options.maxTags > self.itemsArray.length)
        self.$container.removeClass('bootstrap-tagsinput-max');

      self.$element.trigger($.Event('itemRemoved',  { item: item }));
    },

    /**
     * Removes all items
     */
    removeAll: function() {
      var self = this;

      $('.tag', self.$container).remove();
      $('option', self.$element).remove();

      while(self.itemsArray.length > 0)
        self.itemsArray.pop();

      self.pushVal();

      if (self.options.maxTags && !this.isEnabled())
        this.enable();
    },

    /**
     * Refreshes the tags so they match the text/value of their corresponding
     * item.
     */
    refresh: function() {
      var self = this;
      $('.tag', self.$container).each(function() {
        var $tag = $(this),
            item = $tag.data('item'),
            itemValue = self.options.itemValue(item),
            itemText = self.options.itemText(item),
            tagClass = self.options.tagClass(item);

          // Update tag's class and inner text
          $tag.attr('class', null);
          $tag.addClass('tag ' + htmlEncode(tagClass));
          $tag.contents().filter(function() {
            return this.nodeType == 3;
          })[0].nodeValue = htmlEncode(itemText);

          if (self.isSelect) {
            var option = $('option', self.$element).filter(function() { return $(this).data('item') === item; });
            option.attr('value', itemValue);
          }
      });
    },

    /**
     * Returns the items added as tags
     */
    items: function() {
      return this.itemsArray;
    },

    /**
     * Assembly value by retrieving the value of each item, and set it on the
     * element.
     */
    pushVal: function() {
      var self = this,
          val = $.map(self.items(), function(item) {
            return self.options.itemValue(item).toString();
          });

      self.$element.val(val, true).trigger('change');
    },

    /**
     * Initializes the tags input behaviour on the element
     */
    build: function(options) {
      var self = this;

      self.options = $.extend({}, defaultOptions, options);
      var typeahead = self.options.typeahead || {};

      // When itemValue is set, freeInput should always be false
      if (self.objectItems)
        self.options.freeInput = false;

      makeOptionItemFunction(self.options, 'itemValue');
      makeOptionItemFunction(self.options, 'itemText');
      makeOptionItemFunction(self.options, 'tagClass');

      // for backwards compatibility, self.options.source is deprecated
      if (self.options.source)
        typeahead.source = self.options.source;

      if (typeahead.source && $.fn.typeahead) {
        makeOptionFunction(typeahead, 'source');

        self.$input.typeahead({
          source: function (query, process) {
            function processItems(items) {
              var texts = [];

              for (var i = 0; i < items.length; i++) {
                var text = self.options.itemText(items[i]);
                map[text] = items[i];
                texts.push(text);
              }
              process(texts);
            }

            this.map = {};
            var map = this.map,
                data = typeahead.source(query);

            if ($.isFunction(data.success)) {
              // support for Angular promises
              data.success(processItems);
            } else {
              // support for functions and jquery promises
              $.when(data)
               .then(processItems);
            }
          },
          updater: function (text) {
            self.add(this.map[text]);
          },
          matcher: function (text) {
            return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1);
          },
          sorter: function (texts) {
            return texts.sort();
          },
          highlighter: function (text) {
            var regex = new RegExp( '(' + this.query + ')', 'gi' );
            return text.replace( regex, "<strong>$1</strong>" );
          }
        });
      }

      self.$container.on('click', $.proxy(function(event) {
        self.$input.focus();
      }, self));

      self.$container.on('blur', 'input', $.proxy(function(event) {
        var $input = $(event.target);
        self.add($input.val());
        $input.val('');
        event.preventDefault();
      }, self));

      self.$container.on('keydown', 'input', $.proxy(function(event) {
        var $input = $(event.target),
            $inputWrapper = self.findInputWrapper();

        switch (event.which) {
          // BACKSPACE
          case 8:
            if (doGetCaretPosition($input[0]) === 0) {
              var prev = $inputWrapper.prev();
              if (prev) {
                self.remove(prev.data('item'));
              }
            }
            break;

          // DELETE
          case 46:
            if (doGetCaretPosition($input[0]) === 0) {
              var next = $inputWrapper.next();
              if (next) {
                self.remove(next.data('item'));
              }
            }
            break;

          // LEFT ARROW
          case 37:
            // Try to move the input before the previous tag
            var $prevTag = $inputWrapper.prev();
            if ($input.val().length === 0 && $prevTag[0]) {
              $prevTag.before($inputWrapper);
              $input.focus();
            }
            break;
          // RIGHT ARROW
          case 39:
            // Try to move the input after the next tag
            var $nextTag = $inputWrapper.next();
            if ($input.val().length === 0 && $nextTag[0]) {
              $nextTag.after($inputWrapper);
              $input.focus();
            }
            break;
         default:
            // When key corresponds one of the confirmKeys, add current input
            // as a new tag
            if (self.options.freeInput && $.inArray(event.which, self.options.confirmKeys) >= 0) {
              self.add($input.val());
              $input.val('');
              event.preventDefault();
            }
        }

        // Reset internal input's size
        $input.attr('size', Math.max(this.inputSize, $input.val().length));
      }, self));

      // Remove icon clicked
      self.$container.on('click', '[data-role=remove]', $.proxy(function(event) {
        self.remove($(event.target).closest('.tag').data('item'));
        // Grafana mod, if tags input used in popover the click event will bubble up and hide popover
        event.stopPropagation();
      }, self));

      // Only add existing value as tags when using strings as tags
      if (self.options.itemValue === defaultOptions.itemValue) {
        if (self.$element[0].tagName === 'INPUT') {
            self.add(self.$element.val());
        } else {
          $('option', self.$element).each(function() {
            self.add($(this).attr('value'), true);
          });
        }
      }
    },

    /**
     * Removes all tagsinput behaviour and unregsiter all event handlers
     */
    destroy: function() {
      var self = this;

      // Unbind events
      self.$container.off('keypress', 'input');
      self.$container.off('click', '[role=remove]');

      self.$container.remove();
      self.$element.removeData('tagsinput');
      self.$element.show();
    },

    /**
     * Sets focus on the tagsinput
     */
    focus: function() {
      this.$input.focus();
    },

    /**
     * Returns the internal input element
     */
    input: function() {
      return this.$input;
    },

    /**
     * Returns the element which is wrapped around the internal input. This
     * is normally the $container, but typeahead.js moves the $input element.
     */
    findInputWrapper: function() {
      var elt = this.$input[0],
          container = this.$container[0];
      while(elt && elt.parentNode !== container)
        elt = elt.parentNode;

      return $(elt);
    }
  };

  /**
   * Register JQuery plugin
   */
  $.fn.tagsinput = function(arg1, arg2) {
    var results = [];

    this.each(function() {
      var tagsinput = $(this).data('tagsinput');

      // Initialize a new tags input
      if (!tagsinput) {
        tagsinput = new TagsInput(this, arg1);
        $(this).data('tagsinput', tagsinput);
        results.push(tagsinput);

        if (this.tagName === 'SELECT') {
          $('option', $(this)).attr('selected', 'selected');
        }

        // Init tags from $(this).val()
        $(this).val($(this).val());
      } else {
        // Invoke function on existing tags input
        var retVal = tagsinput[arg1](arg2);
        if (retVal !== undefined)
          results.push(retVal);
      }
    });

    if ( typeof arg1 == 'string') {
      // Return the results from the invoked function calls
      return results.length > 1 ? results : results[0];
    } else {
      return results;
    }
  };

  $.fn.tagsinput.Constructor = TagsInput;

  /**
   * Most options support both a string or number as well as a function as
   * option value. This function makes sure that the option with the given
   * key in the given options is wrapped in a function
   */
  function makeOptionItemFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var propertyName = options[key];
      options[key] = function(item) { return item[propertyName]; };
    }
  }
  function makeOptionFunction(options, key) {
    if (typeof options[key] !== 'function') {
      var value = options[key];
      options[key] = function() { return value; };
    }
  }
  /**
   * HtmlEncodes the given value
   */
  var htmlEncodeContainer = $('<div />');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

  /**
   * Returns the position of the caret in the given input field
   * http://flightschool.acylt.com/devnotes/caret-position-woes/
   */
  function doGetCaretPosition(oField) {
    var iCaretPos = 0;
    if (document.selection) {
      oField.focus ();
      var oSel = document.selection.createRange();
      oSel.moveStart ('character', -oField.value.length);
      iCaretPos = oSel.text.length;
    } else if (oField.selectionStart || oField.selectionStart == '0') {
      iCaretPos = oField.selectionStart;
    }
    return (iCaretPos);
  }

  /**
   * Initialize tagsinput behaviour on inputs and selects which have
   * data-role=tagsinput
   */
  $(function() {
    $("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
  });
})(window.jQuery);


/***/ })

}]);
//# sourceMappingURL=default~app.fb2366366adbbbf1d38b.js.map