enchoice-fabric-react-lib
Version:
This project was created to integrate Microsoft Fabric React
1,134 lines (1,098 loc) • 1.91 MB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('axios'), require('react-dom'), require('react-device-detect'), require('immutability-helper'), require('office-ui-fabric-react'), require('@fortawesome/react-fontawesome'), require('file-saver'), require('react-toastify')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'axios', 'react-dom', 'react-device-detect', 'immutability-helper', 'office-ui-fabric-react', '@fortawesome/react-fontawesome', 'file-saver', 'react-toastify'], factory) :
(global = global || self, factory(global.enchoiceFabricReactLib = {}, global.React, global.Axios, global.ReactDOM, global.isMobile, global.update, global.officeUiFabricReact, global.reactFontawesome, global.FileSaver, global.reactToastify));
}(this, function (exports, React, Axios, ReactDOM, isMobile, update, officeUiFabricReact, reactFontawesome, FileSaver, reactToastify) { 'use strict';
Axios = Axios && Axios.hasOwnProperty('default') ? Axios['default'] : Axios;
isMobile = isMobile && isMobile.hasOwnProperty('default') ? isMobile['default'] : isMobile;
update = update && update.hasOwnProperty('default') ? update['default'] : update;
FileSaver = FileSaver && FileSaver.hasOwnProperty('default') ? FileSaver['default'] : FileSaver;
// A packages cache that makes sure that we don't inject the same packageName twice in the same bundle -
// this cache is local to the module closure inside this bundle
var packagesCache = {};
function setVersion(packageName, packageVersion) {
if (typeof window !== 'undefined') {
// tslint:disable-next-line:no-any
var packages = (window.__packages__ = window.__packages__ || {});
// We allow either the global packages or local packages caches to invalidate so testing can just clear the global to set this state
if (!packages[packageName] || !packagesCache[packageName]) {
packagesCache[packageName] = packageVersion;
var versions = (packages[packageName] = packages[packageName] || []);
versions.push(packageVersion);
}
}
}
setVersion('@uifabric/set-version', '6.0.0');
// office-ui-fabric-react@6.167.2
setVersion('office-ui-fabric-react', '6.167.2');
/**
* Bugs often appear in async code when stuff gets disposed, but async operations don't get canceled.
* This Async helper class solves these issues by tying async code to the lifetime of a disposable object.
*
* Usage: Anything class extending from BaseModel can access this helper via this.async. Otherwise create a
* new instance of the class and remember to call dispose() during your code's dispose handler.
*
* @public
*/
var Async = /** @class */ (function () {
// tslint:disable-next-line:no-any
function Async(parent, onError) {
this._timeoutIds = null;
this._immediateIds = null;
this._intervalIds = null;
this._animationFrameIds = null;
this._isDisposed = false;
this._parent = parent || null;
this._onErrorHandler = onError;
this._noop = function () {
/* do nothing */
};
}
/**
* Dispose function, clears all async operations.
*/
Async.prototype.dispose = function () {
var id;
this._isDisposed = true;
this._parent = null;
// Clear timeouts.
if (this._timeoutIds) {
for (id in this._timeoutIds) {
if (this._timeoutIds.hasOwnProperty(id)) {
this.clearTimeout(parseInt(id, 10));
}
}
this._timeoutIds = null;
}
// Clear immediates.
if (this._immediateIds) {
for (id in this._immediateIds) {
if (this._immediateIds.hasOwnProperty(id)) {
this.clearImmediate(parseInt(id, 10));
}
}
this._immediateIds = null;
}
// Clear intervals.
if (this._intervalIds) {
for (id in this._intervalIds) {
if (this._intervalIds.hasOwnProperty(id)) {
this.clearInterval(parseInt(id, 10));
}
}
this._intervalIds = null;
}
// Clear animation frames.
if (this._animationFrameIds) {
for (id in this._animationFrameIds) {
if (this._animationFrameIds.hasOwnProperty(id)) {
this.cancelAnimationFrame(parseInt(id, 10));
}
}
this._animationFrameIds = null;
}
};
/**
* SetTimeout override, which will auto cancel the timeout during dispose.
* @param callback - Callback to execute.
* @param duration - Duration in milliseconds.
* @returns The setTimeout id.
*/
Async.prototype.setTimeout = function (callback, duration) {
var _this = this;
var timeoutId = 0;
if (!this._isDisposed) {
if (!this._timeoutIds) {
this._timeoutIds = {};
}
/* tslint:disable:ban-native-functions */
timeoutId = setTimeout(function () {
// Time to execute the timeout, enqueue it as a foreground task to be executed.
try {
// Now delete the record and call the callback.
if (_this._timeoutIds) {
delete _this._timeoutIds[timeoutId];
}
callback.apply(_this._parent);
}
catch (e) {
if (_this._onErrorHandler) {
_this._onErrorHandler(e);
}
}
}, duration);
/* tslint:enable:ban-native-functions */
this._timeoutIds[timeoutId] = true;
}
return timeoutId;
};
/**
* Clears the timeout.
* @param id - Id to cancel.
*/
Async.prototype.clearTimeout = function (id) {
if (this._timeoutIds && this._timeoutIds[id]) {
/* tslint:disable:ban-native-functions */
clearTimeout(id);
delete this._timeoutIds[id];
/* tslint:enable:ban-native-functions */
}
};
/**
* SetImmediate override, which will auto cancel the immediate during dispose.
* @param callback - Callback to execute.
* @returns The setTimeout id.
*/
Async.prototype.setImmediate = function (callback) {
var _this = this;
var immediateId = 0;
if (!this._isDisposed) {
if (!this._immediateIds) {
this._immediateIds = {};
}
/* tslint:disable:ban-native-functions */
var setImmediateCallback = function () {
// Time to execute the timeout, enqueue it as a foreground task to be executed.
try {
// Now delete the record and call the callback.
if (_this._immediateIds) {
delete _this._immediateIds[immediateId];
}
callback.apply(_this._parent);
}
catch (e) {
_this._logError(e);
}
};
immediateId = window.setImmediate ? window.setImmediate(setImmediateCallback) : window.setTimeout(setImmediateCallback, 0);
/* tslint:enable:ban-native-functions */
this._immediateIds[immediateId] = true;
}
return immediateId;
};
/**
* Clears the immediate.
* @param id - Id to cancel.
*/
Async.prototype.clearImmediate = function (id) {
if (this._immediateIds && this._immediateIds[id]) {
/* tslint:disable:ban-native-functions */
window.clearImmediate ? window.clearImmediate(id) : window.clearTimeout(id);
delete this._immediateIds[id];
/* tslint:enable:ban-native-functions */
}
};
/**
* SetInterval override, which will auto cancel the timeout during dispose.
* @param callback - Callback to execute.
* @param duration - Duration in milliseconds.
* @returns The setTimeout id.
*/
Async.prototype.setInterval = function (callback, duration) {
var _this = this;
var intervalId = 0;
if (!this._isDisposed) {
if (!this._intervalIds) {
this._intervalIds = {};
}
/* tslint:disable:ban-native-functions */
intervalId = setInterval(function () {
// Time to execute the interval callback, enqueue it as a foreground task to be executed.
try {
callback.apply(_this._parent);
}
catch (e) {
_this._logError(e);
}
}, duration);
/* tslint:enable:ban-native-functions */
this._intervalIds[intervalId] = true;
}
return intervalId;
};
/**
* Clears the interval.
* @param id - Id to cancel.
*/
Async.prototype.clearInterval = function (id) {
if (this._intervalIds && this._intervalIds[id]) {
/* tslint:disable:ban-native-functions */
clearInterval(id);
delete this._intervalIds[id];
/* tslint:enable:ban-native-functions */
}
};
/**
* Creates a function that, when executed, will only call the func function at most once per
* every wait milliseconds. Provide an options object to indicate that func should be invoked
* on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled
* function will return the result of the last func call.
*
* Note: If leading and trailing options are true func will be called on the trailing edge of
* the timeout only if the the throttled function is invoked more than once during the wait timeout.
*
* @param func - The function to throttle.
* @param wait - The number of milliseconds to throttle executions to. Defaults to 0.
* @param options - The options object.
* @returns The new throttled function.
*/
Async.prototype.throttle = function (func, wait, options) {
var _this = this;
if (this._isDisposed) {
return this._noop;
}
var waitMS = wait || 0;
var leading = true;
var trailing = true;
var lastExecuteTime = 0;
var lastResult;
// tslint:disable-next-line:no-any
var lastArgs;
var timeoutId = null;
if (options && typeof options.leading === 'boolean') {
leading = options.leading;
}
if (options && typeof options.trailing === 'boolean') {
trailing = options.trailing;
}
var callback = function (userCall) {
var now = new Date().getTime();
var delta = now - lastExecuteTime;
var waitLength = leading ? waitMS - delta : waitMS;
if (delta >= waitMS && (!userCall || leading)) {
lastExecuteTime = now;
if (timeoutId) {
_this.clearTimeout(timeoutId);
timeoutId = null;
}
lastResult = func.apply(_this._parent, lastArgs);
}
else if (timeoutId === null && trailing) {
timeoutId = _this.setTimeout(callback, waitLength);
}
return lastResult;
};
// tslint:disable-next-line:no-any
var resultFunction = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
lastArgs = args;
return callback(true);
};
return resultFunction;
};
/**
* Creates a function that will delay the execution of func until after wait milliseconds have
* elapsed since the last time it was invoked. Provide an options object to indicate that func
* should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls
* to the debounced function will return the result of the last func call.
*
* Note: If leading and trailing options are true func will be called on the trailing edge of
* the timeout only if the the debounced function is invoked more than once during the wait
* timeout.
*
* @param func - The function to debounce.
* @param wait - The number of milliseconds to delay.
* @param options - The options object.
* @returns The new debounced function.
*/
Async.prototype.debounce = function (func, wait, options) {
var _this = this;
if (this._isDisposed) {
var noOpFunction = (function () {
/** Do nothing */
});
noOpFunction.cancel = function () {
return;
};
/* tslint:disable:no-any */
noOpFunction.flush = (function () { return null; });
/* tslint:enable:no-any */
noOpFunction.pending = function () { return false; };
return noOpFunction;
}
var waitMS = wait || 0;
var leading = false;
var trailing = true;
var maxWait = null;
var lastCallTime = 0;
var lastExecuteTime = new Date().getTime();
var lastResult;
// tslint:disable-next-line:no-any
var lastArgs;
var timeoutId = null;
if (options && typeof options.leading === 'boolean') {
leading = options.leading;
}
if (options && typeof options.trailing === 'boolean') {
trailing = options.trailing;
}
if (options && typeof options.maxWait === 'number' && !isNaN(options.maxWait)) {
maxWait = options.maxWait;
}
var markExecuted = function (time) {
if (timeoutId) {
_this.clearTimeout(timeoutId);
timeoutId = null;
}
lastExecuteTime = time;
};
var invokeFunction = function (time) {
markExecuted(time);
lastResult = func.apply(_this._parent, lastArgs);
};
var callback = function (userCall) {
var now = new Date().getTime();
var executeImmediately = false;
if (userCall) {
if (leading && now - lastCallTime >= waitMS) {
executeImmediately = true;
}
lastCallTime = now;
}
var delta = now - lastCallTime;
var waitLength = waitMS - delta;
var maxWaitDelta = now - lastExecuteTime;
var maxWaitExpired = false;
if (maxWait !== null) {
// maxWait only matters when there is a pending callback
if (maxWaitDelta >= maxWait && timeoutId) {
maxWaitExpired = true;
}
else {
waitLength = Math.min(waitLength, maxWait - maxWaitDelta);
}
}
if (delta >= waitMS || maxWaitExpired || executeImmediately) {
invokeFunction(now);
}
else if ((timeoutId === null || !userCall) && trailing) {
timeoutId = _this.setTimeout(callback, waitLength);
}
return lastResult;
};
var pending = function () {
return !!timeoutId;
};
var cancel = function () {
if (pending()) {
// Mark the debounced function as having executed
markExecuted(new Date().getTime());
}
};
var flush = function () {
if (pending()) {
invokeFunction(new Date().getTime());
}
return lastResult;
};
// tslint:disable-next-line:no-any
var resultFunction = (function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
lastArgs = args;
return callback(true);
});
resultFunction.cancel = cancel;
resultFunction.flush = flush;
resultFunction.pending = pending;
return resultFunction;
};
Async.prototype.requestAnimationFrame = function (callback) {
var _this = this;
var animationFrameId = 0;
if (!this._isDisposed) {
if (!this._animationFrameIds) {
this._animationFrameIds = {};
}
/* tslint:disable:ban-native-functions */
var animationFrameCallback = function () {
try {
// Now delete the record and call the callback.
if (_this._animationFrameIds) {
delete _this._animationFrameIds[animationFrameId];
}
callback.apply(_this._parent);
}
catch (e) {
_this._logError(e);
}
};
animationFrameId = window.requestAnimationFrame
? window.requestAnimationFrame(animationFrameCallback)
: window.setTimeout(animationFrameCallback, 0);
/* tslint:enable:ban-native-functions */
this._animationFrameIds[animationFrameId] = true;
}
return animationFrameId;
};
Async.prototype.cancelAnimationFrame = function (id) {
if (this._animationFrameIds && this._animationFrameIds[id]) {
/* tslint:disable:ban-native-functions */
window.cancelAnimationFrame ? window.cancelAnimationFrame(id) : window.clearTimeout(id);
/* tslint:enable:ban-native-functions */
delete this._animationFrameIds[id];
}
};
// tslint:disable-next-line:no-any
Async.prototype._logError = function (e) {
if (this._onErrorHandler) {
this._onErrorHandler(e);
}
};
return Async;
}());
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
}
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
var tslib_1 = /*#__PURE__*/Object.freeze({
__extends: __extends,
get __assign () { return __assign; },
__rest: __rest,
__decorate: __decorate,
__param: __param,
__metadata: __metadata,
__awaiter: __awaiter,
__generator: __generator,
__exportStar: __exportStar,
__values: __values,
__read: __read,
__spread: __spread,
__await: __await,
__asyncGenerator: __asyncGenerator,
__asyncDelegator: __asyncDelegator,
__asyncValues: __asyncValues,
__makeTemplateObject: __makeTemplateObject,
__importStar: __importStar,
__importDefault: __importDefault
});
var InjectionMode = {
/**
* Avoids style injection, use getRules() to read the styles.
*/
none: 0,
/**
* Inserts rules using the insertRule api.
*/
insertNode: 1,
/**
* Appends rules using appendChild.
*/
appendChild: 2
};
var STYLESHEET_SETTING = '__stylesheet__';
// tslint:disable-next-line:no-any
var _fileScopedGlobal = {};
var _stylesheet;
/**
* Represents the state of styles registered in the page. Abstracts
* the surface for adding styles to the stylesheet, exposes helpers
* for reading the styles registered in server rendered scenarios.
*
* @public
*/
var Stylesheet = /** @class */ (function () {
function Stylesheet(config) {
this._rules = [];
this._preservedRules = [];
this._rulesToInsert = [];
this._counter = 0;
this._keyToClassName = {};
this._onResetCallbacks = [];
// tslint:disable-next-line:no-any
this._classNameToArgs = {};
this._config = __assign({ injectionMode: InjectionMode.insertNode, defaultPrefix: 'css', namespace: undefined, cspSettings: undefined }, config);
}
/**
* Gets the singleton instance.
*/
Stylesheet.getInstance = function () {
// tslint:disable-next-line:no-any
var global = typeof window !== 'undefined' ? window : _fileScopedGlobal;
_stylesheet = global[STYLESHEET_SETTING];
if (!_stylesheet || (_stylesheet._lastStyleElement && _stylesheet._lastStyleElement.ownerDocument !== document)) {
// tslint:disable-next-line:no-string-literal
var fabricConfig = (global && global['FabricConfig']) || {};
_stylesheet = global[STYLESHEET_SETTING] = new Stylesheet(fabricConfig.mergeStyles);
}
return _stylesheet;
};
/**
* Configures the stylesheet.
*/
Stylesheet.prototype.setConfig = function (config) {
this._config = __assign({}, this._config, config);
};
/**
* Configures a reset callback.
*
* @param callback - A callback which will be called when the Stylesheet is reset.
*/
Stylesheet.prototype.onReset = function (callback) {
this._onResetCallbacks.push(callback);
};
/**
* Generates a unique classname.
*
* @param displayName - Optional value to use as a prefix.
*/
Stylesheet.prototype.getClassName = function (displayName) {
var namespace = this._config.namespace;
var prefix = displayName || this._config.defaultPrefix;
return "" + (namespace ? namespace + '-' : '') + prefix + "-" + this._counter++;
};
/**
* Used internally to cache information about a class which was
* registered with the stylesheet.
*/
Stylesheet.prototype.cacheClassName = function (className, key, args, rules) {
this._keyToClassName[key] = className;
this._classNameToArgs[className] = {
args: args,
rules: rules
};
};
/**
* Gets the appropriate classname given a key which was previously
* registered using cacheClassName.
*/
Stylesheet.prototype.classNameFromKey = function (key) {
return this._keyToClassName[key];
};
/**
* Gets the arguments associated with a given classname which was
* previously registered using cacheClassName.
*/
Stylesheet.prototype.argsFromClassName = function (className) {
var entry = this._classNameToArgs[className];
return entry && entry.args;
};
/**
* Gets the arguments associated with a given classname which was
* previously registered using cacheClassName.
*/
Stylesheet.prototype.insertedRulesFromClassName = function (className) {
var entry = this._classNameToArgs[className];
return entry && entry.rules;
};
/**
* Inserts a css rule into the stylesheet.
* @param preserve - Preserves the rule beyond a reset boundary.
*/
Stylesheet.prototype.insertRule = function (rule, preserve) {
var injectionMode = this._config.injectionMode;
var element = injectionMode !== InjectionMode.none ? this._getStyleElement() : undefined;
if (preserve) {
this._preservedRules.push(rule);
}
if (element) {
switch (this._config.injectionMode) {
case InjectionMode.insertNode:
var sheet = element.sheet;
try {
sheet.insertRule(rule, sheet.cssRules.length);
}
catch (e) {
// The browser will throw exceptions on unsupported rules (such as a moz prefix in webkit.)
// We need to swallow the exceptions for this scenario, otherwise we'd need to filter
// which could be slower and bulkier.
}
break;
case InjectionMode.appendChild:
element.appendChild(document.createTextNode(rule));
break;
}
}
else {
this._rules.push(rule);
}
if (this._config.onInsertRule) {
this._config.onInsertRule(rule);
}
};
/**
* Gets all rules registered with the stylesheet; only valid when
* using InsertionMode.none.
*/
Stylesheet.prototype.getRules = function (includePreservedRules) {
return (includePreservedRules ? this._preservedRules.join('') : '') + this._rules.join('') + this._rulesToInsert.join('');
};
/**
* Resets the internal state of the stylesheet. Only used in server
* rendered scenarios where we're using InsertionMode.none.
*/
Stylesheet.prototype.reset = function () {
this._rules = [];
this._rulesToInsert = [];
this._counter = 0;
this._classNameToArgs = {};
this._keyToClassName = {};
this._onResetCallbacks.forEach(function (callback) { return callback(); });
};
// Forces the regeneration of incoming styles without totally resetting the stylesheet.
Stylesheet.prototype.resetKeys = function () {
this._keyToClassName = {};
};
Stylesheet.prototype._getStyleElement = function () {
var _this = this;
if (!this._styleElement && typeof document !== 'undefined') {
this._styleElement = this._createStyleElement();
// Reset the style element on the next frame.
window.requestAnimationFrame(function () {
_this._styleElement = undefined;
});
}
return this._styleElement;
};
Stylesheet.prototype._createStyleElement = function () {
var styleElement = document.createElement('style');
styleElement.setAttribute('data-merge-styles', 'true');
styleElement.type = 'text/css';
var cspSettings = this._config.cspSettings;
if (cspSettings) {
if (cspSettings.nonce) {
styleElement.setAttribute('nonce', cspSettings.nonce);
}
}
if (this._lastStyleElement && this._lastStyleElement.nextElementSibling) {
document.head.insertBefore(styleElement, this._lastStyleElement.nextElementSibling);
}
else {
document.head.appendChild(styleElement);
}
this._lastStyleElement = styleElement;
return styleElement;
};
return Stylesheet;
}());
function kebabRules(rulePairs, index) {
rulePairs[index] = rulePairs[index].replace(/([A-Z])/g, '-$1').toLowerCase();
}
var _vendorSettings;
function getVendorSettings() {
if (!_vendorSettings) {
var doc = typeof document !== 'undefined' ? document : undefined;
var nav = typeof navigator !== 'undefined' ? navigator : undefined;
var userAgent = nav ? nav.userAgent.toLowerCase() : undefined;
if (!doc) {
_vendorSettings = {
isWebkit: true,
isMoz: true,
isOpera: true,
isMs: true
};
}
else {
_vendorSettings = {
isWebkit: !!(doc && 'WebkitAppearance' in doc.documentElement.style),
isMoz: !!(userAgent && userAgent.indexOf('firefox') > -1),
isOpera: !!(userAgent && userAgent.indexOf('opera') > -1),
isMs: !!(nav && (/rv:11.0/i.test(nav.userAgent) || /Edge\/\d./i.test(navigator.userAgent)))
};
}
}
return _vendorSettings;
}
var autoPrefixNames = {
'user-select': 1
};
function prefixRules(rulePairs, index) {
var vendorSettings = getVendorSettings();
var name = rulePairs[index];
if (autoPrefixNames[name]) {
var value = rulePairs[index + 1];
if (autoPrefixNames[name]) {
if (vendorSettings.isWebkit) {
rulePairs.push('-webkit-' + name, value);
}
if (vendorSettings.isMoz) {
rulePairs.push('-moz-' + name, value);
}
if (vendorSettings.isMs) {
rulePairs.push('-ms-' + name, value);
}
if (vendorSettings.isOpera) {
rulePairs.push('-o-' + name, value);
}
}
}
}
var NON_PIXEL_NUMBER_PROPS = [
'column-count',
'font-weight',
'flex-basis',
'flex',
'flex-grow',
'flex-shrink',
'fill-opacity',
'opacity',
'order',
'z-index',
'zoom'
];
function provideUnits(rulePairs, index) {
var name = rulePairs[index];
var value = rulePairs[index + 1];
if (typeof value === 'number') {
var unit = NON_PIXEL_NUMBER_PROPS.indexOf(name) === -1 ? 'px' : '';
rulePairs[index + 1] = "" + value + unit;
}
}
var LEFT = 'left';
var RIGHT = 'right';
var NO_FLIP = '@noflip';
var NAME_REPLACEMENTS = (_a = {},
_a[LEFT] = RIGHT,
_a[RIGHT] = LEFT,
_a);
var VALUE_REPLACEMENTS = {
'w-resize': 'e-resize',
'sw-resize': 'se-resize',
'nw-resize': 'ne-resize'
};
var _rtl = getRTL();
/**
* Sets the current RTL value.
*/
function setRTL(isRTL) {
if (_rtl !== isRTL) {
Stylesheet.getInstance().resetKeys();
_rtl = isRTL;
}
}
/**
* Gets the current RTL value.
*/
function getRTL() {
if (_rtl === undefined) {
_rtl = typeof document !== 'undefined' && !!document.documentElement && document.documentElement.getAttribute('dir') === 'rtl';
}
return _rtl;
}
/**
* RTLifies the rulePair in the array at the current index. This mutates the array for performance
* reasons.
*/
function rtlifyRules(rulePairs, index) {
if (getRTL()) {
var name_1 = rulePairs[index];
if (!name_1) {
return;
}
var value = rulePairs[index + 1];
if (typeof value === 'string' && value.indexOf(NO_FLIP) >= 0) {
rulePairs[index + 1] = value.replace(/\s*(?:\/\*\s*)?\@noflip\b(?:\s*\*\/)?\s*?/g, '');
}
else if (name_1.indexOf(LEFT) >= 0) {
rulePairs[index] = name_1.replace(LEFT, RIGHT);
}
else if (name_1.indexOf(RIGHT) >= 0) {
rulePairs[index] = name_1.replace(RIGHT, LEFT);
}
else if (String(value).indexOf(LEFT) >= 0) {
rulePairs[index + 1] = value.replace(LEFT, RIGHT);
}
else if (String(value).indexOf(RIGHT) >= 0) {
rulePairs[index + 1] = value.replace(RIGHT, LEFT);
}
else if (NAME_REPLACEMENTS[name_1]) {
rulePairs[index] = NAME_REPLACEMENTS[name_1];
}
else if (VALUE_REPLACEMENTS[value]) {
rulePairs[index + 1] = VALUE_REPLACEMENTS[value];
}
else {
switch (name_1) {
case 'margin':
case 'padding':
rulePairs[index + 1] = flipQuad(value);
break;
case 'box-shadow':
rulePairs[index + 1] = negateNum(value, 0);
break;
}
}
}
}
/**
* Given a string value in a space delimited format (e.g. "1 2 3 4"), negates a particular value.
*/
function negateNum(value, partIndex) {
var parts = value.split(' ');
var numberVal = parseInt(parts[partIndex], 10);
parts[0] = parts[0].replace(String(numberVal), String(numberVal * -1));
return parts.join(' ');
}
/**
* Given a string quad, flips the left and right values.
*/
function flipQuad(value) {
if (typeof value === 'string') {
var parts = value.split(' ');
if (parts.length === 4) {
return parts[0] + " " + parts[3] + " " + parts[2] + " " + parts[1];
}
}
return value;
}
var _a;
var DISPLAY_NAME = 'displayName';
function getDisplayName(rules) {
var rootStyle = rules && rules['&'];
return rootStyle ? rootStyle.displayName : undefined;
}
var globalSelectorRegExp = /\:global\((.+?)\)/g;
/**
* Finds comma separated selectors in a :global() e.g. ":global(.class1, .class2, .class3)"
* and wraps them each in their own global ":global(.class1), :global(.class2), :global(.class3)"
*
* @param selectorWithGlobals The selector to process
* @returns The updated selector
*/
function expandCommaSeparatedGlobals(selectorWithGlobals) {
// We the selector does not have a :global() we can shortcut
if (!globalSelectorRegExp.test(selectorWithGlobals)) {
return selectorWithGlobals;
}
var replacementInfo = [];
var findGlobal = /\:global\((.+?)\)/g;
var match = null;
// Create a result list for global selectors so we can replace them.
while ((match = findGlobal.exec(selectorWithGlobals))) {
// Only if the found selector is a comma separated list we'll process it.
if (match[1].indexOf(',') > -1) {
replacementInfo.push([
match.index,
match.index + match[0].length,
// Wrap each of the found selectors in :global()
match[1]
.split(',')
.map(function (v) { return ":global(" + v.trim() + ")"; })
.join(', ')
]);
}
}
// Replace the found selectors with their wrapped variants in reverse order
return replacementInfo.reverse().reduce(function (selector, _a) {
var matchIndex = _a[0], matchEndIndex = _a[1], replacement = _a[2];
var prefix = selector.slice(0, matchIndex);
var suffix = selector.slice(matchEndIndex);
return prefix + replacement + suffix;
}, selectorWithGlobals);
}
function expandSelector(newSelector, currentSelector) {
if (newSelector.indexOf(':global(') >= 0) {
return newSelector.replace(globalSelectorRegExp, '$1');
}
else if (newSelector.indexOf(':') === 0) {
return currentSelector + newSelector;
}
else if (newSelector.indexOf('&') < 0) {
return currentSelector + ' ' + newSelector;
}
return newSelector;
}
function extractRules(args, rules, currentSelector) {
if (rules === void 0) { rules = { __order: [] }; }
if (currentSelector === void 0) { currentSelector = '&'; }
var stylesheet = Stylesheet.getInstance();
var currentRules = rules[currentSelector];
if (!currentRules) {
currentRules = {};
rules[currentSelector] = currentRules;
rules.__order.push(currentSelector);
}
for (var _i = 0, args_1 = args; _i < args_1.length; _i++) {
var arg = args_1[_i];
// If the arg is a string, we need to look up the class map and merge.
if (typeof arg === 'string') {
var expandedRules = stylesheet.argsFromClassName(arg);
if (expandedRules) {
extractRules(expandedRules, rules, currentSelector);
}
// Else if the arg is an array, we need to recurse in.
}
else if (Array.isArray(arg)) {
extractRules(arg, rules, currentSelector);
}
else {
// tslint:disable-next-line:no-any
for (var prop in arg) {
if (prop === 'selectors') {
// tslint:disable-next-line:no-any
var selectors = arg.selectors;
for (var newSelector in selectors) {
if (selectors.hasOwnProperty(newSelector)) {
var selectorValue = selectors[newSelector];
if (newSelector.indexOf('@') === 0) {
newSelector = newSelector + '{' + currentSelector;
extractRules([selectorValue], rules, newSelector);
}
else if (newSelector.indexOf(',') > -1) {
var commaSeparatedSelectors = expandCommaSeparatedGlobals(newSelector)
.split(/,/g)