enchoice-fabric-react-lib
Version:
This project was created to integrate Microsoft Fabric React
1,154 lines (1,132 loc) • 1.77 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('@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', '@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.reactFontawesome, global.FileSaver, global.reactToastify));
}(this, function (exports, React, Axios, ReactDOM, isMobile, update, 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.141.1
setVersion('office-ui-fabric-react', '6.141.1');
/**
* 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;
}
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 }, config);
}
/**
* Gets the singleton instance.
*/
Stylesheet.getInstance = function () {
// tslint:disable-next-line:no-any
var global = typeof window !== 'undefined' ? window : typeof process !== 'undefined' ? process : _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';
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)
.map(function (s) { return s.trim(); });
extractRules([selectorValue], rules, commaSeparatedSelectors
.map(function (commaSeparatedSelector) { return expandSelector(commaSeparatedSelector, currentSelector); })
.join(', '));
}
else {
extractRules([selectorValue], rules, expandSelector(newSelector, currentSelector));
}
}
}
}
else {
if (arg[prop] !== undefined) {
// Else, add the rule to the currentSelector.
if (prop === 'margin' || prop === 'padding') {
// tslint:disable-next-line:no-any
expandQuads(currentRules, prop, arg[prop]);
}
else {
// tslint:disable-next-line:no-any
currentRules[prop] = arg[prop];
}
}
}
}
}
}
return rules;
}
function expandQuads(currentRules, name, value) {
var parts = typeof value === 'string' ? value.split(' ') : [value];
currentRules[name + 'Top'] = parts[0];
currentRules[name + 'Right'] = parts[1] || parts[0];
currentRules[name + 'Bottom'] = parts[2] || parts[0];
currentRules[name + 'Left'] = parts[3] || parts[1] || parts[0];
}
function getKeyForRules(rules) {
var serialized = [];
var hasProps = false;
for (var _i = 0, _a = rules.__order; _i < _a.length; _i++) {
var selector = _a[_i];
serialized.push(selector);
var rulesForSelector = rules[selector];
for (var propName in rulesForSelector) {
if (rulesForSelector.hasOwnProperty(propName) && rulesForSelector[propName] !== undefined) {
hasProps = true;
serialized.push(propName, rulesForSelector[propName]);
}
}
}
return hasProps ? serialized.join('') : undefined;
}
function serializeRuleEntries(ruleEntries) {
if (!ruleEntries) {
return '';
}
var allEntries = [];
for (var entry in ruleEntries) {
if (ruleEntries.hasOwnProperty(entry) && entry !== DISPLAY_NAME && ruleEntries[entry] !== undefined) {
allEntries.push(entry, ruleEntries[entry]);
}
}
// Apply transforms.
for (var i = 0; i < allEntries.length; i += 2) {
kebabRules(allEntries, i);
provideUnits(allEntries, i);
rtlifyRules(allEntries, i);
prefixRules(allEntries, i);
}
// Apply punctuation.
for (var i = 1; i < allEntries.length; i += 4) {
allEntries.splice(i, 1, ':', allEntries[i], ';');
}
return allEntries.join('');
}
function styleToRegistration() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var rules = extractRules(args);
var key = getKeyForRules(rules);
if (key) {
var stylesheet = Stylesheet.getInstance();
var registration = {
className: stylesheet.classNameFromKey(key),
key: key,
args: args
};
if (!registration.className) {
registration.className = stylesheet.getClassName(getDisplayName(rules));
var rulesToInsert = [];
for (var _a = 0, _b = rules.__order; _a < _b.length; _a++) {
var selector = _b[_a];
rulesToInsert.push(selector, serializeRuleEntries(rules[selector]));
}
registration.rulesToInsert = rulesToInsert;
}
return registration;
}
}
function applyRegistration(registration, classMap) {
var stylesheet = Stylesheet.getInstance();
var className = registration.className, key = registration.key, args = registration.args, rulesToInsert = registration.rulesToInsert;
if (rulesToInsert) {
// rulesToInsert is an ordered array of selector/rule pairs.
for (var i = 0; i < rulesToInsert.length; i += 2) {
var rules = rulesToInsert[i + 1];
if (rules) {
var selector = rulesToInsert[i];
// Fix selector using map.
selector = selector.replace(/(&)|\$([\w-]+)\b/g, function (match, amp, cn) {
if (amp) {
return '.' + registration.className;
}
else if (cn) {
return '.' + ((classMap && classMap[cn]) || cn);
}
return '';
});
// Insert. Note if a media query, we must close the query with a final bracket.
var processedRule = selector + "{" + rules + "}" + (selector.indexOf('@') === 0 ? '}' : '');
stylesheet.insertRule(processedRule);
}
}
stylesheet.cacheClassName(className, key, args, rulesToInsert);
}
}
function styleToClassName() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var registration = styleToRegistration.apply(void 0, args);
if (registration) {
applyRegistration(registration);
return registration.className;
}
return '';
}
/**
* Separates the classes and style objects. Any classes that are pre-registered
* args are auto expanded into objects.
*/
function extractStyleParts() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var classes = [];
var objects = [];
var stylesheet = Stylesheet.getInstance();
function _processArgs(argsList) {
for (var _i = 0, argsList_1 = argsList; _i < argsList_1.length; _i++) {
var arg = argsList_1[_i];
if (arg) {
if (typeof arg === 'string') {
if (arg.indexOf(' ') >= 0) {
_processArgs(arg.split(' '));
}
else {
var translatedArgs = stylesheet.argsFromClassName(arg);
if (translatedArgs) {
_processArgs(translatedArgs);
}
else {
// Avoid adding the same class twice.
if (classes.indexOf(arg) === -1) {
classes.push(arg);
}
}
}
}
else if (Array.isArray(arg)) {
_processArgs(arg);
}