/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 480); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (false) { module.exports = require('./cjs/react.production.min.js'); } else { module.exports = __webpack_require__(506); } /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js ;(function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory() }(this, (function () { 'use strict'; var hookCallback; function hooks () { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback (callback) { hookCallback = callback; } function isArray(input) { return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; } function isObject(input) { // IE8 will treat undefined and null as object if it wasn't for // input != null return input != null && Object.prototype.toString.call(input) === '[object Object]'; } function isObjectEmpty(obj) { if (Object.getOwnPropertyNames) { return (Object.getOwnPropertyNames(obj).length === 0); } else { var k; for (k in obj) { if (obj.hasOwnProperty(k)) { return false; } } return true; } } function isUndefined(input) { return input === void 0; } function isNumber(input) { return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; } function isDate(input) { return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function createUTC (input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { // We need to deep clone this object. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso : false, parsedDateParts : [], meridiem : null, rfc2822 : false, weekdayMismatch : false }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function (fun) { var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m); var parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }); var isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || (flags.meridiem && parsedParts)); if (m._strict) { isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined; } if (Object.isFrozen == null || !Object.isFrozen(m)) { m._isValid = isNowValid; } else { return isNowValid; } } return m._isValid; } function createInvalid (flags) { var m = createUTC(NaN); if (flags != null) { extend(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = hooks.momentProperties = []; function copyConfig(to, from) { var i, prop, val; if (!isUndefined(from._isAMomentObject)) { to._isAMomentObject = from._isAMomentObject; } if (!isUndefined(from._i)) { to._i = from._i; } if (!isUndefined(from._f)) { to._f = from._f; } if (!isUndefined(from._l)) { to._l = from._l; } if (!isUndefined(from._strict)) { to._strict = from._strict; } if (!isUndefined(from._tzm)) { to._tzm = from._tzm; } if (!isUndefined(from._isUTC)) { to._isUTC = from._isUTC; } if (!isUndefined(from._offset)) { to._offset = from._offset; } if (!isUndefined(from._pf)) { to._pf = getParsingFlags(from); } if (!isUndefined(from._locale)) { to._locale = from._locale; } if (momentProperties.length > 0) { for (i = 0; i < momentProperties.length; i++) { prop = momentProperties[i]; val = from[prop]; if (!isUndefined(val)) { to[prop] = val; } } } return to; } var updateInProgress = false; // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); if (!this.isValid()) { this._d = new Date(NaN); } // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; hooks.updateOffset(this); updateInProgress = false; } } function isMoment (obj) { return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); } function absFloor (number) { if (number < 0) { // -0 -> 0 return Math.ceil(number) || 0; } else { return Math.floor(number); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function warn(msg) { if (hooks.suppressDeprecationWarnings === false && (typeof console !== 'undefined') && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(null, msg); } if (firstTime) { var args = []; var arg; for (var i = 0; i < arguments.length; i++) { arg = ''; if (typeof arguments[i] === 'object') { arg += '\n[' + i + '] '; for (var key in arguments[0]) { arg += key + ': ' + arguments[0][key] + ', '; } arg = arg.slice(0, -2); // Remove trailing comma and space } else { arg = arguments[i]; } args.push(arg); } warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; function isFunction(input) { return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } function set (config) { var prop, i; for (i in config) { prop = config[i]; if (isFunction(prop)) { this[i] = prop; } else { this['_' + i] = prop; } } this._config = config; // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. // TODO: Remove "ordinalParse" fallback in next major release. this._dayOfMonthOrdinalParseLenient = new RegExp( (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + (/\d{1,2}/).source); } function mergeConfigs(parentConfig, childConfig) { var res = extend({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { res[prop] = {}; extend(res[prop], parentConfig[prop]); extend(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) { // make sure changes to properties don't modify parent config res[prop] = extend({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys; if (Object.keys) { keys = Object.keys; } else { keys = function (obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }; function calendar (key, mom, now) { var output = this._calendar[key] || this._calendar['sameElse']; return isFunction(output) ? output.call(mom, now) : output; } var defaultLongDateFormat = { LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A' }; function longDateFormat (key) { var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format || !formatUpper) { return format; } this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate () { return this._invalidDate; } var defaultOrdinal = '%d'; var defaultDayOfMonthOrdinalParse = /\d{1,2}/; function ordinal (number) { return this._ordinal.replace('%d', number); } var defaultRelativeTime = { future : 'in %s', past : '%s ago', s : 'a few seconds', ss : '%d seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }; function relativeTime (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (isFunction(output)) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias (unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = []; for (var u in unitsObj) { units.push({unit: u, priority: priorities[u]}); } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } function zeroFill(number, targetLength, forceSign) { var absNumber = '' + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign = number >= 0; return (sign ? (forceSign ? '+' : '') : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; var formatFunctions = {}; var formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken (token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal(func.apply(this, arguments), token); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = '', i; for (i = 0; i < length; i++) { output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var match1 = /\d/; // 0 - 9 var match2 = /\d\d/; // 00 - 99 var match3 = /\d{3}/; // 000 - 999 var match4 = /\d{4}/; // 0000 - 9999 var match6 = /[+-]?\d{6}/; // -999999 - 999999 var match1to2 = /\d\d?/; // 0 - 99 var match3to4 = /\d\d\d\d?/; // 999 - 9999 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 var match1to3 = /\d{1,3}/; // 0 - 999 var match1to4 = /\d{1,4}/; // 0 - 9999 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 var matchUnsigned = /\d+/; // 0 - inf var matchSigned = /[+-]?\d+/; // -inf - inf var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. // includes scottish gaelic two word and hyphenated months var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; var regexes = {}; function addRegexToken (token, regex, strictRegex) { regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { return (isStrict && strictRegex) ? strictRegex : regex; }; } function getParseRegexForToken (token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; })); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken (token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (isNumber(callback)) { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken (token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0; var MONTH = 1; var DATE = 2; var HOUR = 3; var MINUTE = 4; var SECOND = 5; var MILLISECOND = 6; var WEEK = 7; var WEEKDAY = 8; // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? '' + y : '+' + y; }); addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PRIORITIES addUnitPriority('year', 1); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYYY', 'YYYYYY'], YEAR); addParseToken('YYYY', function (input, array) { array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken('YY', function (input, array) { array[YEAR] = hooks.parseTwoDigitYear(input); }); addParseToken('Y', function (input, array) { array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // HOOKS hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', true); function getIsLeapYear () { return isLeapYear(this.year()); } function makeGetSet (unit, keepTime) { return function (value) { if (value != null) { set$1(this, unit, value); hooks.updateOffset(this, keepTime); return this; } else { return get(this, unit); } }; } function get (mom, unit) { return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; } function set$1 (mom, unit, value) { if (mom.isValid() && !isNaN(value)) { if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); } else { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } } // MOMENTS function stringGet (units) { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](); } return this; } function stringSet (units, value) { if (typeof units === 'object') { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units); for (var i = 0; i < prioritized.length; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } function mod(n, x) { return ((n % x) + x) % x; } var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function (o) { // I know var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { if (isNaN(year) || isNaN(month)) { return NaN; } var modMonth = mod(month, 12); year += (month - modMonth) / 12; return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PRIORITY addUnitPriority('month', 8); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', function (isStrict, locale) { return locale.monthsShortRegex(isStrict); }); addRegexToken('MMMM', function (isStrict, locale) { return locale.monthsRegex(isStrict); }); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); // LOCALES var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); function localeMonths (m, format) { if (!m) { return isArray(this._months) ? this._months : this._months['standalone']; } return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; } var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); function localeMonthsShort (m, format) { if (!m) { return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone']; } return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; } function handleStrictParse(monthName, format, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { // this is not used this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = createUTC([2000, i]); this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse (monthName, format, strict) { var i, mom, regex; if (this._monthsParseExact) { return handleStrictParse.call(this, monthName, format, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } // TODO: add sorting // Sorting makes sure if one month (or abbr) is a prefix of another // see sorting in computeMonthsParse for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth (mom, value) { var dayOfMonth; if (!mom.isValid()) { // No op return mom; } if (typeof value === 'string') { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (!isNumber(value)) { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth (value) { if (value != null) { setMonth(this, value); hooks.updateOffset(this, true); return this; } else { return get(this, 'Month'); } } function getDaysInMonth () { return daysInMonth(this.year(), this.month()); } var defaultMonthsShortRegex = matchWord; function monthsShortRegex (isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, '_monthsShortRegex')) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } var defaultMonthsRegex = matchWord; function monthsRegex (isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, '_monthsRegex')) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse () { function cmpLenRev(a, b) { return b.length - a.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); shortPieces.push(this.monthsShort(mom, '')); longPieces.push(this.months(mom, '')); mixedPieces.push(this.months(mom, '')); mixedPieces.push(this.monthsShort(mom, '')); } // Sorting makes sure if one month (or abbr) is a prefix of another it // will match the longer piece. shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); } function createDate (y, m, d, h, M, s, ms) { // can't just apply() to create a date: // https://stackoverflow.com/q/181348 var date = new Date(y, m, d, h, M, s, ms); // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { date.setFullYear(y); } return date; } function createUTCDate (y) { var date = new Date(Date.UTC.apply(null, arguments)); // the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { var // first-week day -- which january is always in the first week (4 for iso, 1 for other) fwd = 7 + dow - doy, // first-week day local weekday -- which local weekday is fwd fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PRIORITIES addUnitPriority('week', 5); addUnitPriority('isoWeek', 5); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // LOCALES function localeWeek (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 6th is the first week of the year. }; function localeFirstDayOfWeek () { return this._week.dow; } function localeFirstDayOfYear () { return this._week.doy; } // MOMENTS function getSetWeek (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); function localeWeekdays (m, format) { if (!m) { return isArray(this._weekdays) ? this._weekdays : this._weekdays['standalone']; } return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; } var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); function localeWeekdaysShort (m) { return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; } var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); function localeWeekdaysMin (m) { return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; } function handleStrictParse$1(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse (weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse$1.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i'); this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i'); this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i'); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } var defaultWeekdaysRegex = matchWord; function weekdaysRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } var defaultWeekdaysShortRegex = matchWord; function weekdaysShortRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } var defaultWeekdaysMinRegex = matchWord; function weekdaysMinRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse () { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); minp = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = this.weekdays(mom, ''); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); } // FORMATTING function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, hFormat); addFormatToken('k', ['kk', 2], 0, kFormat); addFormatToken('hmm', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken('hmmss', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); addFormatToken('Hmm', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken('Hmmss', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); function meridiem (token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PRIORITY addUnitPriority('hour', 13); // PARSING function matchMeridiem (isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('k', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addRegexToken('kk', match1to2, match2); addRegexToken('hmm', match3to4); addRegexToken('hmmss', match5to6); addRegexToken('Hmm', match3to4); addRegexToken('Hmmss', match5to6); addParseToken(['H', 'HH'], HOUR); addParseToken(['k', 'kk'], function (input, array, config) { var kInput = toInt(input); array[HOUR] = kInput === 24 ? 0 : kInput; }); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken('hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken('hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken('Hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken('Hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; function localeMeridiem (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } // MOMENTS // Setting the hour should keep the time, because the user explicitly // specified which hour they want. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. var getSetHour = makeGetSet('Hours', true); var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse }; // internal storage for locale config files var locales = {}; var localeFamilies = {}; var globalLocale; function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return globalLocale; } function loadLocale(name) { var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node if (!locales[name] && (typeof module !== 'undefined') && module && module.exports) { try { oldLocale = globalLocale._abbr; var aliasedRequire = require; __webpack_require__(508)("./" + name); getSetGlobalLocale(oldLocale); } catch (e) {} } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function getSetGlobalLocale (key, values) { var data; if (key) { if (isUndefined(values)) { data = getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } else { if ((typeof console !== 'undefined') && console.warn) { //warn user if arguments are passed but the locale could not be set console.warn('Locale ' + key + ' not found. Did you forget to load it?'); } } } return globalLocale._abbr; } function defineLocale (name, config) { if (config !== null) { var locale, parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { locale = loadLocale(config.parentLocale); if (locale != null) { parentConfig = locale._config; } else { if (!localeFamilies[config.parentLocale]) { localeFamilies[config.parentLocale] = []; } localeFamilies[config.parentLocale].push({ name: name, config: config }); return null; } } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); if (localeFamilies[name]) { localeFamilies[name].forEach(function (x) { defineLocale(x.name, x.config); }); } // backwards compat for now: also set the locale // make sure we set the locale AFTER all child locales have been // created, so we won't end up with the child locale set. getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale, tmpLocale, parentConfig = baseConfig; // MERGE tmpLocale = loadLocale(name); if (tmpLocale != null) { parentConfig = tmpLocale._config; } config = mergeConfigs(parentConfig, config); locale = new Locale(config); locale.parentLocale = locales[name]; locales[name] = locale; // backwards compat for now: also set the locale getSetGlobalLocale(name); } else { // pass null for config to unupdate, useful for tests if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } // returns locale data function getLocale (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } function listLocales() { return keys(locales); } function checkOverflow (m) { var overflow; var a = m._a; if (a && getParsingFlags(m).overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { // hooks is actually the exported moment object var nowValue = new Date(hooks.now()); if (config._useUTC) { return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray (config) { var i, date, input = [], currentDate, expectedWeekday, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear != null) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } // check for mismatching day of week if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { getParsingFlags(config).weekdayMismatch = true; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); week = defaults(w.W, 1); weekday = defaults(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; var curWeek = weekOfYear(createLocal(), dow, doy); weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week. week = defaults(w.w, curWeek.week); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { // local weekday -- counting starts from beginning of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to beginning of week weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; var isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/] ]; // iso time formats and regexes var isoTimes = [ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/] ]; var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(match[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match[3]) { for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(match[3])) { // match[2] should be 'T' or space timeFormat = (match[2] || ' ') + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match[4]) { if (tzRegex.exec(match[4])) { tzFormat = 'Z'; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); configFromStringAndFormat(config); } else { config._isValid = false; } } // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { var result = [ untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10) ]; if (secondStr) { result.push(parseInt(secondStr, 10)); } return result; } function untruncateYear(yearStr) { var year = parseInt(yearStr, 10); if (year <= 49) { return 2000 + year; } else if (year <= 999) { return 1900 + year; } return year; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } function checkWeekday(weekdayStr, parsedInput, config) { if (weekdayStr) { // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); if (weekdayProvided !== weekdayActual) { getParsingFlags(config).weekdayMismatch = true; config._isValid = false; return false; } } return true; } var obsOffsets = { UT: 0, GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function calculateOffset(obsOffset, militaryOffset, numOffset) { if (obsOffset) { return obsOffsets[obsOffset]; } else if (militaryOffset) { // the only allowed military tz is Z return 0; } else { var hm = parseInt(numOffset, 10); var m = hm % 100, h = (hm - m) / 100; return h * 60 + m; } } // date and time from ref 2822 format function configFromRFC2822(config) { var match = rfc2822.exec(preprocessRFC2822(config._i)); if (match) { var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); if (!checkWeekday(match[1], parsedArray, config)) { return; } config._a = parsedArray; config._tzm = calculateOffset(match[8], match[9], match[10]); config._d = createUTCDate.apply(null, config._a); config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); getParsingFlags(config).rfc2822 = true; } else { config._isValid = false; } } // date from iso format or fallback function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; } else { return; } configFromRFC2822(config); if (config._isValid === false) { delete config._isValid; } else { return; } // Final attempt, use Input Fallback hooks.createFromInputFallback(config); } hooks.createFromInputFallback = deprecate( 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged and will be removed in an upcoming major release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // constant that refers to the ISO standard hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form hooks.RFC_2822 = function () {}; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === hooks.ISO_8601) { configFromISO(config); return; } if (config._f === hooks.RFC_2822) { configFromRFC2822(config); return; } config._a = []; getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput, // 'regex', getParseRegexForToken(token, config)); if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token); } } // add remaining unparsed input length to the string getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { getParsingFlags(config).unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) { getParsingFlags(config).bigHour = undefined; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; // handle meridiem config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); configFromArray(config); checkOverflow(config); } function meridiemFixWrap (locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } // date from string and array of format strings function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i); config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { return obj && parseInt(obj, 10); }); configFromArray(config); } function createFromConfig (config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function prepareConfig (config) { var input = config._i, format = config._f; config._locale = config._locale || getLocale(config._l); if (input === null || (format === undefined && input === '')) { return createInvalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isDate(input)) { config._d = input; } else if (isArray(format)) { configFromStringAndArray(config); } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (isUndefined(input)) { config._d = new Date(hooks.now()); } else if (isDate(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (isObject(input)) { configFromObject(config); } else if (isNumber(input)) { // from milliseconds config._d = new Date(input); } else { hooks.createFromInputFallback(config); } } function createLocalOrUTC (input, format, locale, strict, isUTC) { var c = {}; if (locale === true || locale === false) { strict = locale; locale = undefined; } if ((isObject(input) && isObjectEmpty(input)) || (isArray(input) && input.length === 0)) { input = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; return createFromConfig(c); } function createLocal (input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return createInvalid(); } } ); var prototypeMax = deprecate( 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return createInvalid(); } } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } var now = function () { return Date.now ? Date.now() : +(new Date()); }; var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; function isDurationValid(m) { for (var key in m) { if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { return false; } } var unitHasDecimal = false; for (var i = 0; i < ordering.length; ++i) { if (m[ordering[i]]) { if (unitHasDecimal) { return false; // only allow non-integers for smallest unit } if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { unitHasDecimal = true; } } } return true; } function isValid$1() { return this._isValid; } function createInvalid$1() { return createDuration(NaN); } function Duration (duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || normalizedInput.isoWeek || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = getLocale(); this._bubble(); } function isDuration (obj) { return obj instanceof Duration; } function absRound (number) { if (number < 0) { return Math.round(-1 * number) * -1; } else { return Math.round(number); } } // FORMATTING function offset (token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(); var sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchShortOffset); addRegexToken('ZZ', matchShortOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { var matches = (string || '').match(matcher); if (matches === null) { return null; } var chunk = matches[matches.length - 1] || []; var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; var minutes = +(parts[1] * 60) + toInt(parts[2]); return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api. res._d.setTime(res._d.valueOf() + diff); hooks.updateOffset(res, false); return res; } else { return createLocal(input).local(); } } function getDateOffset (m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. hooks.updateOffset = function () {}; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset (input, keepLocalTime, keepMinutes) { var offset = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === 'string') { input = offsetFromString(matchShortOffset, input); if (input === null) { return this; } } else if (Math.abs(input) < 16 && !keepMinutes) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addSubtract(this, createDuration(input - offset, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone (input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC (keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal (keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset () { if (this._tzm != null) { this.utcOffset(this._tzm, false, true); } else if (typeof this._i === 'string') { var tZone = offsetFromString(matchOffset, this._i); if (tZone != null) { this.utcOffset(tZone); } else { this.utcOffset(0, true); } } return this; } function hasAlignedHourOffset (input) { if (!this.isValid()) { return false; } input = input ? createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime () { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted () { if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}; copyConfig(c, this); c = prepareConfig(c); if (c._a) { var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal () { return this.isValid() ? !this._isUTC : false; } function isUtcOffset () { return this.isValid() ? this._isUTC : false; } function isUtc () { return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function createDuration (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms : input._milliseconds, d : input._days, M : input._months }; } else if (isNumber(input)) { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : 0, d : toInt(match[DATE]) * sign, h : toInt(match[HOUR]) * sign, m : toInt(match[MINUTE]) * sign, s : toInt(match[SECOND]) * sign, ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match }; } else if (!!(match = isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : parseIso(match[2], sign), M : parseIso(match[3], sign), w : parseIso(match[4], sign), d : parseIso(match[5], sign), h : parseIso(match[6], sign), m : parseIso(match[7], sign), s : parseIso(match[8], sign) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } createDuration.fn = Duration.prototype; createDuration.invalid = createInvalid$1; function parseIso (inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return {milliseconds: 0, months: 0}; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = createDuration(val, period); addSubtract(this, dur, direction); return this; }; } function addSubtract (mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months); if (!mom.isValid()) { // No op return; } updateOffset = updateOffset == null ? true : updateOffset; if (months) { setMonth(mom, get(mom, 'Month') + months * isAdding); } if (days) { set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); } if (milliseconds) { mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); } if (updateOffset) { hooks.updateOffset(mom, days || months); } } var add = createAdder(1, 'add'); var subtract = createAdder(-1, 'subtract'); function getCalendarFormat(myMoment, now) { var diff = myMoment.diff(now, 'days', true); return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; } function calendar$1 (time, formats) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = hooks.calendarFormat(this, sod) || 'sameElse'; var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); return this.format(output || this.localeData().calendar(format, this, createLocal(now))); } function clone () { return new Moment(this); } function isAfter (input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore (input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween (from, to, units, inclusivity) { var localFrom = isMoment(from) ? from : createLocal(from), localTo = isMoment(to) ? to : createLocal(to); if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { return false; } inclusivity = inclusivity || '()'; return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); } function isSame (input, units) { var localInput = isMoment(input) ? input : createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); } } function isSameOrAfter (input, units) { return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore (input, units) { return this.isSame(input, units) || this.isBefore(input, units); } function diff (input, units, asFloat) { var that, zoneDelta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); switch (units) { case 'year': output = monthDiff(this, that) / 12; break; case 'month': output = monthDiff(this, that); break; case 'quarter': output = monthDiff(this, that) / 3; break; case 'second': output = (this - that) / 1e3; break; // 1000 case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst default: output = this - that; } return asFloat ? output : absFloor(output); } function monthDiff (a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } //check for negative zero, return zero if negative zero return -(wholeMonthDiff + adjust) || 0; } hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; function toString () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function toISOString(keepOffset) { if (!this.isValid()) { return null; } var utc = keepOffset !== true; var m = utc ? this.clone().utc() : this; if (m.year() < 0 || m.year() > 9999) { return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); } if (isFunction(Date.prototype.toISOString)) { // native implementation is ~50x faster, use it when we can if (utc) { return this.toDate().toISOString(); } else { return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z')); } } return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); } /** * Return a human readable representation of a moment that can * also be evaluated to get a new moment which is the same * * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects */ function inspect () { if (!this.isValid()) { return 'moment.invalid(/* ' + this._i + ' */)'; } var func = 'moment'; var zone = ''; if (!this.isLocal()) { func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; zone = 'Z'; } var prefix = '[' + func + '("]'; var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; var datetime = '-MM-DD[T]HH:mm:ss.SSS'; var suffix = zone + '[")]'; return this.format(prefix + year + datetime + suffix); } function format (inputString) { if (!inputString) { inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from (time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid())) { return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow (withoutSuffix) { return this.from(createLocal(), withoutSuffix); } function to (time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid())) { return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow (withoutSuffix) { return this.to(createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData () { return this._locale; } function startOf (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': case 'date': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); } // weeks are a special case if (units === 'week') { this.weekday(0); } if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; } function endOf (units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } // 'date' is an alias for 'day', so it should be considered as such. if (units === 'date') { units = 'day'; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); } function valueOf () { return this._d.valueOf() - ((this._offset || 0) * 60000); } function unix () { return Math.floor(this.valueOf() / 1000); } function toDate () { return new Date(this.valueOf()); } function toArray () { var m = this; return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; } function toObject () { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds() }; } function toJSON () { // new Date(NaN).toJSON() === null return this.isValid() ? this.toISOString() : null; } function isValid$2 () { return isValid(this); } function parsingFlags () { return extend({}, getParsingFlags(this)); } function invalidAt () { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict }; } // FORMATTING addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken (token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PRIORITY addUnitPriority('weekYear', 1); addUnitPriority('isoWeekYear', 1); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear (input) { return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy); } function getSetISOWeekYear (input) { return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4); } function getISOWeeksInYear () { return weeksInYear(this.year(), 1, 4); } function getWeeksInYear () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } // FORMATTING addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PRIORITY addUnitPriority('quarter', 7); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); } // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIORITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { // TODO: Remove "ordinalParse" fallback in next major release. return isStrict ? (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0]); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PRIORITY addUnitPriority('dayOfYear', 4); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS // MOMENTS function getSetDayOfYear (input) { var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); } // FORMATTING addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PRIORITY addUnitPriority('minute', 14); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PRIORITY addUnitPriority('second', 15); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); // FORMATTING addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); addFormatToken(0, ['SSS', 3], 0, 'millisecond'); addFormatToken(0, ['SSSS', 4], 0, function () { return this.millisecond() * 10; }); addFormatToken(0, ['SSSSS', 5], 0, function () { return this.millisecond() * 100; }); addFormatToken(0, ['SSSSSS', 6], 0, function () { return this.millisecond() * 1000; }); addFormatToken(0, ['SSSSSSS', 7], 0, function () { return this.millisecond() * 10000; }); addFormatToken(0, ['SSSSSSSS', 8], 0, function () { return this.millisecond() * 100000; }); addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { return this.millisecond() * 1000000; }); // ALIASES addUnitAlias('millisecond', 'ms'); // PRIORITY addUnitPriority('millisecond', 16); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); var token; for (token = 'SSSS'; token.length <= 9; token += 'S') { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); } for (token = 'S'; token.length <= 9; token += 'S') { addParseToken(token, parseMs); } // MOMENTS var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr () { return this._isUTC ? 'UTC' : ''; } function getZoneName () { return this._isUTC ? 'Coordinated Universal Time' : ''; } var proto = Moment.prototype; proto.add = add; proto.calendar = calendar$1; proto.clone = clone; proto.diff = diff; proto.endOf = endOf; proto.format = format; proto.from = from; proto.fromNow = fromNow; proto.to = to; proto.toNow = toNow; proto.get = stringGet; proto.invalidAt = invalidAt; proto.isAfter = isAfter; proto.isBefore = isBefore; proto.isBetween = isBetween; proto.isSame = isSame; proto.isSameOrAfter = isSameOrAfter; proto.isSameOrBefore = isSameOrBefore; proto.isValid = isValid$2; proto.lang = lang; proto.locale = locale; proto.localeData = localeData; proto.max = prototypeMax; proto.min = prototypeMin; proto.parsingFlags = parsingFlags; proto.set = stringSet; proto.startOf = startOf; proto.subtract = subtract; proto.toArray = toArray; proto.toObject = toObject; proto.toDate = toDate; proto.toISOString = toISOString; proto.inspect = inspect; proto.toJSON = toJSON; proto.toString = toString; proto.unix = unix; proto.valueOf = valueOf; proto.creationData = creationData; proto.year = getSetYear; proto.isLeapYear = getIsLeapYear; proto.weekYear = getSetWeekYear; proto.isoWeekYear = getSetISOWeekYear; proto.quarter = proto.quarters = getSetQuarter; proto.month = getSetMonth; proto.daysInMonth = getDaysInMonth; proto.week = proto.weeks = getSetWeek; proto.isoWeek = proto.isoWeeks = getSetISOWeek; proto.weeksInYear = getWeeksInYear; proto.isoWeeksInYear = getISOWeeksInYear; proto.date = getSetDayOfMonth; proto.day = proto.days = getSetDayOfWeek; proto.weekday = getSetLocaleDayOfWeek; proto.isoWeekday = getSetISODayOfWeek; proto.dayOfYear = getSetDayOfYear; proto.hour = proto.hours = getSetHour; proto.minute = proto.minutes = getSetMinute; proto.second = proto.seconds = getSetSecond; proto.millisecond = proto.milliseconds = getSetMillisecond; proto.utcOffset = getSetOffset; proto.utc = setOffsetToUTC; proto.local = setOffsetToLocal; proto.parseZone = setOffsetToParsedOffset; proto.hasAlignedHourOffset = hasAlignedHourOffset; proto.isDST = isDaylightSavingTime; proto.isLocal = isLocal; proto.isUtcOffset = isUtcOffset; proto.isUtc = isUtc; proto.isUTC = isUtc; proto.zoneAbbr = getZoneAbbr; proto.zoneName = getZoneName; proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); function createUnix (input) { return createLocal(input * 1000); } function createInZone () { return createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat (string) { return string; } var proto$1 = Locale.prototype; proto$1.calendar = calendar; proto$1.longDateFormat = longDateFormat; proto$1.invalidDate = invalidDate; proto$1.ordinal = ordinal; proto$1.preparse = preParsePostFormat; proto$1.postformat = preParsePostFormat; proto$1.relativeTime = relativeTime; proto$1.pastFuture = pastFuture; proto$1.set = set; proto$1.months = localeMonths; proto$1.monthsShort = localeMonthsShort; proto$1.monthsParse = localeMonthsParse; proto$1.monthsRegex = monthsRegex; proto$1.monthsShortRegex = monthsShortRegex; proto$1.week = localeWeek; proto$1.firstDayOfYear = localeFirstDayOfYear; proto$1.firstDayOfWeek = localeFirstDayOfWeek; proto$1.weekdays = localeWeekdays; proto$1.weekdaysMin = localeWeekdaysMin; proto$1.weekdaysShort = localeWeekdaysShort; proto$1.weekdaysParse = localeWeekdaysParse; proto$1.weekdaysRegex = weekdaysRegex; proto$1.weekdaysShortRegex = weekdaysShortRegex; proto$1.weekdaysMinRegex = weekdaysMinRegex; proto$1.isPM = localeIsPM; proto$1.meridiem = localeMeridiem; function get$1 (format, index, field, setter) { var locale = getLocale(); var utc = createUTC().set(setter, index); return locale[field](utc, format); } function listMonthsImpl (format, index, field) { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; if (index != null) { return get$1(format, index, field, 'month'); } var i; var out = []; for (i = 0; i < 12; i++) { out[i] = get$1(format, i, field, 'month'); } return out; } // () // (5) // (fmt, 5) // (fmt) // (true) // (true, 5) // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl (localeSorted, format, index, field) { if (typeof localeSorted === 'boolean') { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } else { format = localeSorted; index = format; localeSorted = false; if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } var locale = getLocale(), shift = localeSorted ? locale._week.dow : 0; if (index != null) { return get$1(format, (index + shift) % 7, field, 'day'); } var i; var out = []; for (i = 0; i < 7; i++) { out[i] = get$1(format, (i + shift) % 7, field, 'day'); } return out; } function listMonths (format, index) { return listMonthsImpl(format, index, 'months'); } function listMonthsShort (format, index) { return listMonthsImpl(format, index, 'monthsShort'); } function listWeekdays (localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } function listWeekdaysShort (localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } function listWeekdaysMin (localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } getSetGlobalLocale('en', { dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // Side effect imports hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); var mathAbs = Math.abs; function abs () { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function addSubtract$1 (duration, input, value, direction) { var other = createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function add$1 (input, value) { return addSubtract$1(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function subtract$1 (input, value) { return addSubtract$1(this, input, value, -1); } function absCeil (number) { if (number < 0) { return Math.floor(number); } else { return Math.ceil(number); } } function bubble () { var milliseconds = this._milliseconds; var days = this._days; var months = this._months; var data = this._data; var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first // check: https://github.com/moment/moment/issues/2166 if (!((milliseconds >= 0 && days >= 0 && months >= 0) || (milliseconds <= 0 && days <= 0 && months <= 0))) { milliseconds += absCeil(monthsToDays(months) + days) * 864e5; days = 0; months = 0; } // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // convert days to months monthsFromDays = absFloor(daysToMonths(days)); months += monthsFromDays; days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year years = absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToMonths (days) { // 400 years have 146097 days (taking into account leap year rules) // 400 years have 12 months === 4800 return days * 4800 / 146097; } function monthsToDays (months) { // the reverse of daysToMonths return months * 146097 / 4800; } function as (units) { if (!this.isValid()) { return NaN; } var days; var months; var milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(monthsToDays(this._months)); switch (units) { case 'week' : return days / 7 + milliseconds / 6048e5; case 'day' : return days + milliseconds / 864e5; case 'hour' : return days * 24 + milliseconds / 36e5; case 'minute' : return days * 1440 + milliseconds / 6e4; case 'second' : return days * 86400 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 864e5) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function valueOf$1 () { if (!this.isValid()) { return NaN; } return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs (alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'); var asSeconds = makeAs('s'); var asMinutes = makeAs('m'); var asHours = makeAs('h'); var asDays = makeAs('d'); var asWeeks = makeAs('w'); var asMonths = makeAs('M'); var asYears = makeAs('y'); function clone$1 () { return createDuration(this); } function get$2 (units) { units = normalizeUnits(units); return this.isValid() ? this[units + 's']() : NaN; } function makeGetter(name) { return function () { return this.isValid() ? this._data[name] : NaN; }; } var milliseconds = makeGetter('milliseconds'); var seconds = makeGetter('seconds'); var minutes = makeGetter('minutes'); var hours = makeGetter('hours'); var days = makeGetter('days'); var months = makeGetter('months'); var years = makeGetter('years'); function weeks () { return absFloor(this.days() / 7); } var round = Math.round; var thresholds = { ss: 44, // a few seconds to seconds s : 45, // seconds to minute m : 45, // minutes to hour h : 22, // hours to day d : 26, // days to month M : 11 // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime$1 (posNegDuration, withoutSuffix, locale) { var duration = createDuration(posNegDuration).abs(); var seconds = round(duration.as('s')); var minutes = round(duration.as('m')); var hours = round(duration.as('h')); var days = round(duration.as('d')); var months = round(duration.as('M')); var years = round(duration.as('y')); var a = seconds <= thresholds.ss && ['s', seconds] || seconds < thresholds.s && ['ss', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function getSetRelativeTimeRounding (roundingFunction) { if (roundingFunction === undefined) { return round; } if (typeof(roundingFunction) === 'function') { round = roundingFunction; return true; } return false; } // This function allows you to set a threshold for relative time strings function getSetRelativeTimeThreshold (threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; if (threshold === 's') { thresholds.ss = limit - 1; } return true; } function humanize (withSuffix) { if (!this.isValid()) { return this.localeData().invalidDate(); } var locale = this.localeData(); var output = relativeTime$1(this, !withSuffix, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var abs$1 = Math.abs; function sign(x) { return ((x > 0) - (x < 0)) || +x; } function toISOString$1() { // for ISO strings we do not use the normal bubbling rules: // * milliseconds bubble up until they become hours // * days do not bubble at all // * months bubble up until they become years // This is because there is no context-free conversion between hours and days // (think of clock changes) // and also not between days and months (28-31 days per month) if (!this.isValid()) { return this.localeData().invalidDate(); } var seconds = abs$1(this._milliseconds) / 1000; var days = abs$1(this._days); var months = abs$1(this._months); var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour minutes = absFloor(seconds / 60); hours = absFloor(minutes / 60); seconds %= 60; minutes %= 60; // 12 months -> 1 year years = absFloor(months / 12); months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var Y = years; var M = months; var D = days; var h = hours; var m = minutes; var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; var total = this.asSeconds(); if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } var totalSign = total < 0 ? '-' : ''; var ymSign = sign(this._months) !== sign(total) ? '-' : ''; var daysSign = sign(this._days) !== sign(total) ? '-' : ''; var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; return totalSign + 'P' + (Y ? ymSign + Y + 'Y' : '') + (M ? ymSign + M + 'M' : '') + (D ? daysSign + D + 'D' : '') + ((h || m || s) ? 'T' : '') + (h ? hmsSign + h + 'H' : '') + (m ? hmsSign + m + 'M' : '') + (s ? hmsSign + s + 'S' : ''); } var proto$2 = Duration.prototype; proto$2.isValid = isValid$1; proto$2.abs = abs; proto$2.add = add$1; proto$2.subtract = subtract$1; proto$2.as = as; proto$2.asMilliseconds = asMilliseconds; proto$2.asSeconds = asSeconds; proto$2.asMinutes = asMinutes; proto$2.asHours = asHours; proto$2.asDays = asDays; proto$2.asWeeks = asWeeks; proto$2.asMonths = asMonths; proto$2.asYears = asYears; proto$2.valueOf = valueOf$1; proto$2._bubble = bubble; proto$2.clone = clone$1; proto$2.get = get$2; proto$2.milliseconds = milliseconds; proto$2.seconds = seconds; proto$2.minutes = minutes; proto$2.hours = hours; proto$2.days = days; proto$2.weeks = weeks; proto$2.months = months; proto$2.years = years; proto$2.humanize = humanize; proto$2.toISOString = toISOString$1; proto$2.toString = toISOString$1; proto$2.toJSON = toISOString$1; proto$2.locale = locale; proto$2.localeData = localeData; proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); proto$2.lang = lang; // Side effect imports // FORMATTING addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input, 10) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); // Side effect imports hooks.version = '2.23.0'; setHookCallback(createLocal); hooks.fn = proto; hooks.min = min; hooks.max = max; hooks.now = now; hooks.utc = createUTC; hooks.unix = createUnix; hooks.months = listMonths; hooks.isDate = isDate; hooks.locale = getSetGlobalLocale; hooks.invalid = createInvalid; hooks.duration = createDuration; hooks.isMoment = isMoment; hooks.weekdays = listWeekdays; hooks.parseZone = createInZone; hooks.localeData = getLocale; hooks.isDuration = isDuration; hooks.monthsShort = listMonthsShort; hooks.weekdaysMin = listWeekdaysMin; hooks.defineLocale = defineLocale; hooks.updateLocale = updateLocale; hooks.locales = listLocales; hooks.weekdaysShort = listWeekdaysShort; hooks.normalizeUnits = normalizeUnits; hooks.relativeTimeRounding = getSetRelativeTimeRounding; hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; hooks.calendarFormat = getCalendarFormat; hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats hooks.HTML5_FMT = { DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // DATE: 'YYYY-MM-DD', // TIME: 'HH:mm', // TIME_SECONDS: 'HH:mm:ss', // TIME_MS: 'HH:mm:ss.SSS', // WEEK: 'GGGG-[W]WW', // MONTH: 'YYYY-MM' // }; return hooks; }))); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(71)(module))) /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(507)(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = require('./factoryWithThrowingShims')(); } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg) && arg.length) { var inner = classNames.apply(null, arg); if (inner) { classes.push(inner); } } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { classNames.default = classNames; module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { return classNames; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _typeof2 = __webpack_require__(61); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _setPrototypeOf = __webpack_require__(553); var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); var _create = __webpack_require__(557); var _create2 = _interopRequireDefault(_create); var _typeof2 = __webpack_require__(61); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); } subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _assign = __webpack_require__(525); var _assign2 = _interopRequireDefault(_assign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _assign2.default || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function checkDCE() { /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' ) { return; } if (true) { // This branch is unreachable because this function is only called // in production, but the condition is true only in development. // Therefore if the branch is still here, dead code elimination wasn't // properly applied. // Don't change the message. React DevTools relies on it. Also make sure // this message doesn't occur elsewhere in this function, or it will cause // a false positive. throw new Error('^_^'); } try { // Verify that the code above has been dead code eliminated (DCE'd). __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); } catch (err) { // DevTools shouldn't crash React, no matter what. // We should still report in case we break this code. console.error(err); } } if (false) { // DCE check should happen before ReactDOM bundle executes so that // DevTools can report bad minification during injection. checkDCE(); module.exports = require('./cjs/react-dom.production.min.js'); } else { module.exports = __webpack_require__(520); } /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.Immutable = factory(); }(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; function createClass(ctor, superClass) { if (superClass) { ctor.prototype = Object.create(superClass.prototype); } ctor.prototype.constructor = ctor; } function Iterable(value) { return isIterable(value) ? value : Seq(value); } createClass(KeyedIterable, Iterable); function KeyedIterable(value) { return isKeyed(value) ? value : KeyedSeq(value); } createClass(IndexedIterable, Iterable); function IndexedIterable(value) { return isIndexed(value) ? value : IndexedSeq(value); } createClass(SetIterable, Iterable); function SetIterable(value) { return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); } function isIterable(maybeIterable) { return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); } function isKeyed(maybeKeyed) { return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); } function isIndexed(maybeIndexed) { return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); } function isAssociative(maybeAssociative) { return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); } function isOrdered(maybeOrdered) { return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); } Iterable.isIterable = isIterable; Iterable.isKeyed = isKeyed; Iterable.isIndexed = isIndexed; Iterable.isAssociative = isAssociative; Iterable.isOrdered = isOrdered; Iterable.Keyed = KeyedIterable; Iterable.Indexed = IndexedIterable; Iterable.Set = SetIterable; var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; // Used for setting prototype methods that IE8 chokes on. var DELETE = 'delete'; // Constants describing the size of trie nodes. var SHIFT = 5; // Resulted in best performance after ______? var SIZE = 1 << SHIFT; var MASK = SIZE - 1; // A consistent shared value representing "not set" which equals nothing other // than itself, and nothing that could be provided externally. var NOT_SET = {}; // Boolean references, Rough equivalent of `bool &`. var CHANGE_LENGTH = { value: false }; var DID_ALTER = { value: false }; function MakeRef(ref) { ref.value = false; return ref; } function SetRef(ref) { ref && (ref.value = true); } // A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {} // http://jsperf.com/copy-array-inline function arrCopy(arr, offset) { offset = offset || 0; var len = Math.max(0, arr.length - offset); var newArr = new Array(len); for (var ii = 0; ii < len; ii++) { newArr[ii] = arr[ii + offset]; } return newArr; } function ensureSize(iter) { if (iter.size === undefined) { iter.size = iter.__iterate(returnTrue); } return iter.size; } function wrapIndex(iter, index) { // This implements "is array index" which the ECMAString spec defines as: // // A String property name P is an array index if and only if // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal // to 2^32−1. // // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects if (typeof index !== 'number') { var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 if ('' + uint32Index !== index || uint32Index === 4294967295) { return NaN; } index = uint32Index; } return index < 0 ? ensureSize(iter) + index : index; } function returnTrue() { return true; } function wholeSlice(begin, end, size) { return (begin === 0 || (size !== undefined && begin <= -size)) && (end === undefined || (size !== undefined && end >= size)); } function resolveBegin(begin, size) { return resolveIndex(begin, size, 0); } function resolveEnd(end, size) { return resolveIndex(end, size, size); } function resolveIndex(index, size, defaultIndex) { return index === undefined ? defaultIndex : index < 0 ? Math.max(0, size + index) : size === undefined ? index : Math.min(size, index); } /* global Symbol */ var ITERATE_KEYS = 0; var ITERATE_VALUES = 1; var ITERATE_ENTRIES = 2; var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; function Iterator(next) { this.next = next; } Iterator.prototype.toString = function() { return '[Iterator]'; }; Iterator.KEYS = ITERATE_KEYS; Iterator.VALUES = ITERATE_VALUES; Iterator.ENTRIES = ITERATE_ENTRIES; Iterator.prototype.inspect = Iterator.prototype.toSource = function () { return this.toString(); } Iterator.prototype[ITERATOR_SYMBOL] = function () { return this; }; function iteratorValue(type, k, v, iteratorResult) { var value = type === 0 ? k : type === 1 ? v : [k, v]; iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { value: value, done: false }); return iteratorResult; } function iteratorDone() { return { value: undefined, done: true }; } function hasIterator(maybeIterable) { return !!getIteratorFn(maybeIterable); } function isIterator(maybeIterator) { return maybeIterator && typeof maybeIterator.next === 'function'; } function getIterator(iterable) { var iteratorFn = getIteratorFn(iterable); return iteratorFn && iteratorFn.call(iterable); } function getIteratorFn(iterable) { var iteratorFn = iterable && ( (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || iterable[FAUX_ITERATOR_SYMBOL] ); if (typeof iteratorFn === 'function') { return iteratorFn; } } function isArrayLike(value) { return value && typeof value.length === 'number'; } createClass(Seq, Iterable); function Seq(value) { return value === null || value === undefined ? emptySequence() : isIterable(value) ? value.toSeq() : seqFromValue(value); } Seq.of = function(/*...values*/) { return Seq(arguments); }; Seq.prototype.toSeq = function() { return this; }; Seq.prototype.toString = function() { return this.__toString('Seq {', '}'); }; Seq.prototype.cacheResult = function() { if (!this._cache && this.__iterateUncached) { this._cache = this.entrySeq().toArray(); this.size = this._cache.length; } return this; }; // abstract __iterateUncached(fn, reverse) Seq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, true); }; // abstract __iteratorUncached(type, reverse) Seq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, true); }; createClass(KeyedSeq, Seq); function KeyedSeq(value) { return value === null || value === undefined ? emptySequence().toKeyedSeq() : isIterable(value) ? (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : keyedSeqFromValue(value); } KeyedSeq.prototype.toKeyedSeq = function() { return this; }; createClass(IndexedSeq, Seq); function IndexedSeq(value) { return value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); } IndexedSeq.of = function(/*...values*/) { return IndexedSeq(arguments); }; IndexedSeq.prototype.toIndexedSeq = function() { return this; }; IndexedSeq.prototype.toString = function() { return this.__toString('Seq [', ']'); }; IndexedSeq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, false); }; IndexedSeq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, false); }; createClass(SetSeq, Seq); function SetSeq(value) { return ( value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value ).toSetSeq(); } SetSeq.of = function(/*...values*/) { return SetSeq(arguments); }; SetSeq.prototype.toSetSeq = function() { return this; }; Seq.isSeq = isSeq; Seq.Keyed = KeyedSeq; Seq.Set = SetSeq; Seq.Indexed = IndexedSeq; var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; Seq.prototype[IS_SEQ_SENTINEL] = true; createClass(ArraySeq, IndexedSeq); function ArraySeq(array) { this._array = array; this.size = array.length; } ArraySeq.prototype.get = function(index, notSetValue) { return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; ArraySeq.prototype.__iterate = function(fn, reverse) { var array = this._array; var maxIndex = array.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { return ii + 1; } } return ii; }; ArraySeq.prototype.__iterator = function(type, reverse) { var array = this._array; var maxIndex = array.length - 1; var ii = 0; return new Iterator(function() {return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} ); }; createClass(ObjectSeq, KeyedSeq); function ObjectSeq(object) { var keys = Object.keys(object); this._object = object; this._keys = keys; this.size = keys.length; } ObjectSeq.prototype.get = function(key, notSetValue) { if (notSetValue !== undefined && !this.has(key)) { return notSetValue; } return this._object[key]; }; ObjectSeq.prototype.has = function(key) { return this._object.hasOwnProperty(key); }; ObjectSeq.prototype.__iterate = function(fn, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var key = keys[reverse ? maxIndex - ii : ii]; if (fn(object[key], key, this) === false) { return ii + 1; } } return ii; }; ObjectSeq.prototype.__iterator = function(type, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; var ii = 0; return new Iterator(function() { var key = keys[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, key, object[key]); }); }; ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; createClass(IterableSeq, IndexedSeq); function IterableSeq(iterable) { this._iterable = iterable; this.size = iterable.length || iterable.size; } IterableSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); var iterations = 0; if (isIterator(iterator)) { var step; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } } return iterations; }; IterableSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); if (!isIterator(iterator)) { return new Iterator(iteratorDone); } var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; createClass(IteratorSeq, IndexedSeq); function IteratorSeq(iterator) { this._iterator = iterator; this._iteratorCache = []; } IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; while (iterations < cache.length) { if (fn(cache[iterations], iterations++, this) === false) { return iterations; } } var step; while (!(step = iterator.next()).done) { var val = step.value; cache[iterations] = val; if (fn(val, iterations++, this) === false) { break; } } return iterations; }; IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; return new Iterator(function() { if (iterations >= cache.length) { var step = iterator.next(); if (step.done) { return step; } cache[iterations] = step.value; } return iteratorValue(type, iterations, cache[iterations++]); }); }; // # pragma Helper functions function isSeq(maybeSeq) { return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); } var EMPTY_SEQ; function emptySequence() { return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } function keyedSeqFromValue(value) { var seq = Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : typeof value === 'object' ? new ObjectSeq(value) : undefined; if (!seq) { throw new TypeError( 'Expected Array or iterable object of [k, v] entries, '+ 'or keyed object: ' + value ); } return seq; } function indexedSeqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values: ' + value ); } return seq; } function seqFromValue(value) { var seq = maybeIndexedSeqFromValue(value) || (typeof value === 'object' && new ObjectSeq(value)); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values, or keyed object: ' + value ); } return seq; } function maybeIndexedSeqFromValue(value) { return ( isArrayLike(value) ? new ArraySeq(value) : isIterator(value) ? new IteratorSeq(value) : hasIterator(value) ? new IterableSeq(value) : undefined ); } function seqIterate(seq, fn, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var entry = cache[reverse ? maxIndex - ii : ii]; if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { return ii + 1; } } return ii; } return seq.__iterateUncached(fn, reverse); } function seqIterator(seq, type, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; var ii = 0; return new Iterator(function() { var entry = cache[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); }); } return seq.__iteratorUncached(type, reverse); } function fromJS(json, converter) { return converter ? fromJSWith(converter, json, '', {'': json}) : fromJSDefault(json); } function fromJSWith(converter, json, key, parentJSON) { if (Array.isArray(json)) { return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } if (isPlainObj(json)) { return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } return json; } function fromJSDefault(json) { if (Array.isArray(json)) { return IndexedSeq(json).map(fromJSDefault).toList(); } if (isPlainObj(json)) { return KeyedSeq(json).map(fromJSDefault).toMap(); } return json; } function isPlainObj(value) { return value && (value.constructor === Object || value.constructor === undefined); } /** * An extension of the "same-value" algorithm as [described for use by ES6 Map * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) * * NaN is considered the same as NaN, however -0 and 0 are considered the same * value, which is different from the algorithm described by * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * This is extended further to allow Objects to describe the values they * represent, by way of `valueOf` or `equals` (and `hashCode`). * * Note: because of this extension, the key equality of Immutable.Map and the * value equality of Immutable.Set will differ from ES6 Map and Set. * * ### Defining custom values * * The easiest way to describe the value an object represents is by implementing * `valueOf`. For example, `Date` represents a value by returning a unix * timestamp for `valueOf`: * * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... * var date2 = new Date(1234567890000); * date1.valueOf(); // 1234567890000 * assert( date1 !== date2 ); * assert( Immutable.is( date1, date2 ) ); * * Note: overriding `valueOf` may have other implications if you use this object * where JavaScript expects a primitive, such as implicit string coercion. * * For more complex types, especially collections, implementing `valueOf` may * not be performant. An alternative is to implement `equals` and `hashCode`. * * `equals` takes another object, presumably of similar type, and returns true * if the it is equal. Equality is symmetrical, so the same result should be * returned if this and the argument are flipped. * * assert( a.equals(b) === b.equals(a) ); * * `hashCode` returns a 32bit integer number representing the object which will * be used to determine how to store the value object in a Map or Set. You must * provide both or neither methods, one must not exist without the other. * * Also, an important relationship between these methods must be upheld: if two * values are equal, they *must* return the same hashCode. If the values are not * equal, they might have the same hashCode; this is called a hash collision, * and while undesirable for performance reasons, it is acceptable. * * if (a.equals(b)) { * assert( a.hashCode() === b.hashCode() ); * } * * All Immutable collections implement `equals` and `hashCode`. * */ function is(valueA, valueB) { if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } if (typeof valueA.valueOf === 'function' && typeof valueB.valueOf === 'function') { valueA = valueA.valueOf(); valueB = valueB.valueOf(); if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } } if (typeof valueA.equals === 'function' && typeof valueB.equals === 'function' && valueA.equals(valueB)) { return true; } return false; } function deepEqual(a, b) { if (a === b) { return true; } if ( !isIterable(b) || a.size !== undefined && b.size !== undefined && a.size !== b.size || a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || isKeyed(a) !== isKeyed(b) || isIndexed(a) !== isIndexed(b) || isOrdered(a) !== isOrdered(b) ) { return false; } if (a.size === 0 && b.size === 0) { return true; } var notAssociative = !isAssociative(a); if (isOrdered(a)) { var entries = a.entries(); return b.every(function(v, k) { var entry = entries.next().value; return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); }) && entries.next().done; } var flipped = false; if (a.size === undefined) { if (b.size === undefined) { if (typeof a.cacheResult === 'function') { a.cacheResult(); } } else { flipped = true; var _ = a; a = b; b = _; } } var allEqual = true; var bSize = b.__iterate(function(v, k) { if (notAssociative ? !a.has(v) : flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { allEqual = false; return false; } }); return allEqual && a.size === bSize; } createClass(Repeat, IndexedSeq); function Repeat(value, times) { if (!(this instanceof Repeat)) { return new Repeat(value, times); } this._value = value; this.size = times === undefined ? Infinity : Math.max(0, times); if (this.size === 0) { if (EMPTY_REPEAT) { return EMPTY_REPEAT; } EMPTY_REPEAT = this; } } Repeat.prototype.toString = function() { if (this.size === 0) { return 'Repeat []'; } return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; }; Repeat.prototype.get = function(index, notSetValue) { return this.has(index) ? this._value : notSetValue; }; Repeat.prototype.includes = function(searchValue) { return is(this._value, searchValue); }; Repeat.prototype.slice = function(begin, end) { var size = this.size; return wholeSlice(begin, end, size) ? this : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); }; Repeat.prototype.reverse = function() { return this; }; Repeat.prototype.indexOf = function(searchValue) { if (is(this._value, searchValue)) { return 0; } return -1; }; Repeat.prototype.lastIndexOf = function(searchValue) { if (is(this._value, searchValue)) { return this.size; } return -1; }; Repeat.prototype.__iterate = function(fn, reverse) { for (var ii = 0; ii < this.size; ii++) { if (fn(this._value, ii, this) === false) { return ii + 1; } } return ii; }; Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; var ii = 0; return new Iterator(function() {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} ); }; Repeat.prototype.equals = function(other) { return other instanceof Repeat ? is(this._value, other._value) : deepEqual(other); }; var EMPTY_REPEAT; function invariant(condition, error) { if (!condition) throw new Error(error); } createClass(Range, IndexedSeq); function Range(start, end, step) { if (!(this instanceof Range)) { return new Range(start, end, step); } invariant(step !== 0, 'Cannot step a Range by 0'); start = start || 0; if (end === undefined) { end = Infinity; } step = step === undefined ? 1 : Math.abs(step); if (end < start) { step = -step; } this._start = start; this._end = end; this._step = step; this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); if (this.size === 0) { if (EMPTY_RANGE) { return EMPTY_RANGE; } EMPTY_RANGE = this; } } Range.prototype.toString = function() { if (this.size === 0) { return 'Range []'; } return 'Range [ ' + this._start + '...' + this._end + (this._step > 1 ? ' by ' + this._step : '') + ' ]'; }; Range.prototype.get = function(index, notSetValue) { return this.has(index) ? this._start + wrapIndex(this, index) * this._step : notSetValue; }; Range.prototype.includes = function(searchValue) { var possibleIndex = (searchValue - this._start) / this._step; return possibleIndex >= 0 && possibleIndex < this.size && possibleIndex === Math.floor(possibleIndex); }; Range.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } begin = resolveBegin(begin, this.size); end = resolveEnd(end, this.size); if (end <= begin) { return new Range(0, 0); } return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); }; Range.prototype.indexOf = function(searchValue) { var offsetValue = searchValue - this._start; if (offsetValue % this._step === 0) { var index = offsetValue / this._step; if (index >= 0 && index < this.size) { return index } } return -1; }; Range.prototype.lastIndexOf = function(searchValue) { return this.indexOf(searchValue); }; Range.prototype.__iterate = function(fn, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(value, ii, this) === false) { return ii + 1; } value += reverse ? -step : step; } return ii; }; Range.prototype.__iterator = function(type, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; var ii = 0; return new Iterator(function() { var v = value; value += reverse ? -step : step; return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); }); }; Range.prototype.equals = function(other) { return other instanceof Range ? this._start === other._start && this._end === other._end && this._step === other._step : deepEqual(this, other); }; var EMPTY_RANGE; createClass(Collection, Iterable); function Collection() { throw TypeError('Abstract'); } createClass(KeyedCollection, Collection);function KeyedCollection() {} createClass(IndexedCollection, Collection);function IndexedCollection() {} createClass(SetCollection, Collection);function SetCollection() {} Collection.Keyed = KeyedCollection; Collection.Indexed = IndexedCollection; Collection.Set = SetCollection; var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? Math.imul : function imul(a, b) { a = a | 0; // int b = b | 0; // int var c = a & 0xffff; var d = b & 0xffff; // Shift by 0 fixes the sign on the high part. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int }; // v8 has an optimization for storing 31-bit signed numbers. // Values which have either 00 or 11 as the high order bits qualify. // This function drops the highest order bit in a signed number, maintaining // the sign bit. function smi(i32) { return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); } function hash(o) { if (o === false || o === null || o === undefined) { return 0; } if (typeof o.valueOf === 'function') { o = o.valueOf(); if (o === false || o === null || o === undefined) { return 0; } } if (o === true) { return 1; } var type = typeof o; if (type === 'number') { var h = o | 0; if (h !== o) { h ^= o * 0xFFFFFFFF; } while (o > 0xFFFFFFFF) { o /= 0xFFFFFFFF; h ^= o; } return smi(h); } if (type === 'string') { return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); } if (typeof o.hashCode === 'function') { return o.hashCode(); } if (type === 'object') { return hashJSObj(o); } if (typeof o.toString === 'function') { return hashString(o.toString()); } throw new Error('Value type ' + type + ' cannot be hashed.'); } function cachedHashString(string) { var hash = stringHashCache[string]; if (hash === undefined) { hash = hashString(string); if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { STRING_HASH_CACHE_SIZE = 0; stringHashCache = {}; } STRING_HASH_CACHE_SIZE++; stringHashCache[string] = hash; } return hash; } // http://jsperf.com/hashing-strings function hashString(string) { // This is the hash from JVM // The hash code for a string is computed as // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], // where s[i] is the ith character of the string and n is the length of // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 // (exclusive) by dropping high bits. var hash = 0; for (var ii = 0; ii < string.length; ii++) { hash = 31 * hash + string.charCodeAt(ii) | 0; } return smi(hash); } function hashJSObj(obj) { var hash; if (usingWeakMap) { hash = weakMap.get(obj); if (hash !== undefined) { return hash; } } hash = obj[UID_HASH_KEY]; if (hash !== undefined) { return hash; } if (!canDefineProperty) { hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; if (hash !== undefined) { return hash; } hash = getIENodeHash(obj); if (hash !== undefined) { return hash; } } hash = ++objHashUID; if (objHashUID & 0x40000000) { objHashUID = 0; } if (usingWeakMap) { weakMap.set(obj, hash); } else if (isExtensible !== undefined && isExtensible(obj) === false) { throw new Error('Non-extensible objects are not allowed as keys.'); } else if (canDefineProperty) { Object.defineProperty(obj, UID_HASH_KEY, { 'enumerable': false, 'configurable': false, 'writable': false, 'value': hash }); } else if (obj.propertyIsEnumerable !== undefined && obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { // Since we can't define a non-enumerable property on the object // we'll hijack one of the less-used non-enumerable properties to // save our hash on it. Since this is a function it will not show up in // `JSON.stringify` which is what we want. obj.propertyIsEnumerable = function() { return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); }; obj.propertyIsEnumerable[UID_HASH_KEY] = hash; } else if (obj.nodeType !== undefined) { // At this point we couldn't get the IE `uniqueID` to use as a hash // and we couldn't use a non-enumerable property to exploit the // dontEnum bug so we simply add the `UID_HASH_KEY` on the node // itself. obj[UID_HASH_KEY] = hash; } else { throw new Error('Unable to set a non-enumerable property on object.'); } return hash; } // Get references to ES5 object methods. var isExtensible = Object.isExtensible; // True if Object.defineProperty works as expected. IE8 fails this test. var canDefineProperty = (function() { try { Object.defineProperty({}, '@', {}); return true; } catch (e) { return false; } }()); // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it // and avoid memory leaks from the IE cloneNode bug. function getIENodeHash(node) { if (node && node.nodeType > 0) { switch (node.nodeType) { case 1: // Element return node.uniqueID; case 9: // Document return node.documentElement && node.documentElement.uniqueID; } } } // If possible, use a WeakMap. var usingWeakMap = typeof WeakMap === 'function'; var weakMap; if (usingWeakMap) { weakMap = new WeakMap(); } var objHashUID = 0; var UID_HASH_KEY = '__immutablehash__'; if (typeof Symbol === 'function') { UID_HASH_KEY = Symbol(UID_HASH_KEY); } var STRING_HASH_CACHE_MIN_STRLEN = 16; var STRING_HASH_CACHE_MAX_SIZE = 255; var STRING_HASH_CACHE_SIZE = 0; var stringHashCache = {}; function assertNotInfinite(size) { invariant( size !== Infinity, 'Cannot perform this action with an infinite size.' ); } createClass(Map, KeyedCollection); // @pragma Construction function Map(value) { return value === null || value === undefined ? emptyMap() : isMap(value) && !isOrdered(value) ? value : emptyMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } Map.prototype.toString = function() { return this.__toString('Map {', '}'); }; // @pragma Access Map.prototype.get = function(k, notSetValue) { return this._root ? this._root.get(0, undefined, k, notSetValue) : notSetValue; }; // @pragma Modification Map.prototype.set = function(k, v) { return updateMap(this, k, v); }; Map.prototype.setIn = function(keyPath, v) { return this.updateIn(keyPath, NOT_SET, function() {return v}); }; Map.prototype.remove = function(k) { return updateMap(this, k, NOT_SET); }; Map.prototype.deleteIn = function(keyPath) { return this.updateIn(keyPath, function() {return NOT_SET}); }; Map.prototype.update = function(k, notSetValue, updater) { return arguments.length === 1 ? k(this) : this.updateIn([k], notSetValue, updater); }; Map.prototype.updateIn = function(keyPath, notSetValue, updater) { if (!updater) { updater = notSetValue; notSetValue = undefined; } var updatedValue = updateInDeepMap( this, forceIterator(keyPath), notSetValue, updater ); return updatedValue === NOT_SET ? undefined : updatedValue; }; Map.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }; // @pragma Composition Map.prototype.merge = function(/*...iters*/) { return mergeIntoMapWith(this, undefined, arguments); }; Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, merger, iters); }; Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.merge === 'function' ? m.merge.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoMapWith(this, deepMerger, arguments); }; Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, deepMergerWith(merger), iters); }; Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.mergeDeep === 'function' ? m.mergeDeep.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.sort = function(comparator) { // Late binding return OrderedMap(sortFactory(this, comparator)); }; Map.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedMap(sortFactory(this, comparator, mapper)); }; // @pragma Mutability Map.prototype.withMutations = function(fn) { var mutable = this.asMutable(); fn(mutable); return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; }; Map.prototype.asMutable = function() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); }; Map.prototype.asImmutable = function() { return this.__ensureOwner(); }; Map.prototype.wasAltered = function() { return this.__altered; }; Map.prototype.__iterator = function(type, reverse) { return new MapIterator(this, type, reverse); }; Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; this._root && this._root.iterate(function(entry ) { iterations++; return fn(entry[1], entry[0], this$0); }, reverse); return iterations; }; Map.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }; function isMap(maybeMap) { return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); } Map.isMap = isMap; var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; var MapPrototype = Map.prototype; MapPrototype[IS_MAP_SENTINEL] = true; MapPrototype[DELETE] = MapPrototype.remove; MapPrototype.removeIn = MapPrototype.deleteIn; // #pragma Trie Nodes function ArrayMapNode(ownerID, entries) { this.ownerID = ownerID; this.entries = entries; } ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && entries.length === 1) { return; // undefined } if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { return createNodes(ownerID, entries, key, value); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new ArrayMapNode(ownerID, newEntries); }; function BitmapIndexedNode(ownerID, bitmap, nodes) { this.ownerID = ownerID; this.bitmap = bitmap; this.nodes = nodes; } BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); var bitmap = this.bitmap; return (bitmap & bit) === 0 ? notSetValue : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); }; BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var bit = 1 << keyHashFrag; var bitmap = this.bitmap; var exists = (bitmap & bit) !== 0; if (!exists && value === NOT_SET) { return this; } var idx = popCount(bitmap & (bit - 1)); var nodes = this.nodes; var node = exists ? nodes[idx] : undefined; var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); } if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { return nodes[idx ^ 1]; } if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { return newNode; } var isEditable = ownerID && ownerID === this.ownerID; var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; var newNodes = exists ? newNode ? setIn(nodes, idx, newNode, isEditable) : spliceOut(nodes, idx, isEditable) : spliceIn(nodes, idx, newNode, isEditable); if (isEditable) { this.bitmap = newBitmap; this.nodes = newNodes; return this; } return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; function HashArrayMapNode(ownerID, count, nodes) { this.ownerID = ownerID; this.count = count; this.nodes = nodes; } HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var node = this.nodes[idx]; return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; }; HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var removed = value === NOT_SET; var nodes = this.nodes; var node = nodes[idx]; if (removed && !node) { return this; } var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } var newCount = this.count; if (!node) { newCount++; } else if (!newNode) { newCount--; if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { return packNodes(ownerID, nodes, newCount, idx); } } var isEditable = ownerID && ownerID === this.ownerID; var newNodes = setIn(nodes, idx, newNode, isEditable); if (isEditable) { this.count = newCount; this.nodes = newNodes; return this; } return new HashArrayMapNode(ownerID, newCount, newNodes); }; function HashCollisionNode(ownerID, keyHash, entries) { this.ownerID = ownerID; this.keyHash = keyHash; this.entries = entries; } HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var removed = value === NOT_SET; if (keyHash !== this.keyHash) { if (removed) { return this; } SetRef(didAlter); SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); } var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && len === 2) { return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new HashCollisionNode(ownerID, this.keyHash, newEntries); }; function ValueNode(ownerID, keyHash, entry) { this.ownerID = ownerID; this.keyHash = keyHash; this.entry = entry; } ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { return is(key, this.entry[0]) ? this.entry[1] : notSetValue; }; ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var keyMatch = is(key, this.entry[0]); if (keyMatch ? value === this.entry[1] : removed) { return this; } SetRef(didAlter); if (removed) { SetRef(didChangeSize); return; // undefined } if (keyMatch) { if (ownerID && ownerID === this.ownerID) { this.entry[1] = value; return this; } return new ValueNode(ownerID, this.keyHash, [key, value]); } SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); }; // #pragma Iterators ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) { var entries = this.entries; for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { return false; } } } BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) { var nodes = this.nodes; for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { var node = nodes[reverse ? maxIndex - ii : ii]; if (node && node.iterate(fn, reverse) === false) { return false; } } } ValueNode.prototype.iterate = function (fn, reverse) { return fn(this.entry); } createClass(MapIterator, Iterator); function MapIterator(map, type, reverse) { this._type = type; this._reverse = reverse; this._stack = map._root && mapIteratorFrame(map._root); } MapIterator.prototype.next = function() { var type = this._type; var stack = this._stack; while (stack) { var node = stack.node; var index = stack.index++; var maxIndex; if (node.entry) { if (index === 0) { return mapIteratorValue(type, node.entry); } } else if (node.entries) { maxIndex = node.entries.length - 1; if (index <= maxIndex) { return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); } } else { maxIndex = node.nodes.length - 1; if (index <= maxIndex) { var subNode = node.nodes[this._reverse ? maxIndex - index : index]; if (subNode) { if (subNode.entry) { return mapIteratorValue(type, subNode.entry); } stack = this._stack = mapIteratorFrame(subNode, stack); } continue; } } stack = this._stack = this._stack.__prev; } return iteratorDone(); }; function mapIteratorValue(type, entry) { return iteratorValue(type, entry[0], entry[1]); } function mapIteratorFrame(node, prev) { return { node: node, index: 0, __prev: prev }; } function makeMap(size, root, ownerID, hash) { var map = Object.create(MapPrototype); map.size = size; map._root = root; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_MAP; function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); } function updateMap(map, k, v) { var newRoot; var newSize; if (!map._root) { if (v === NOT_SET) { return map; } newSize = 1; newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); } else { var didChangeSize = MakeRef(CHANGE_LENGTH); var didAlter = MakeRef(DID_ALTER); newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); if (!didAlter.value) { return map; } newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); } if (map.__ownerID) { map.size = newSize; map._root = newRoot; map.__hash = undefined; map.__altered = true; return map; } return newRoot ? makeMap(newSize, newRoot) : emptyMap(); } function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (!node) { if (value === NOT_SET) { return node; } SetRef(didAlter); SetRef(didChangeSize); return new ValueNode(ownerID, keyHash, [key, value]); } return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); } function isLeafNode(node) { return node.constructor === ValueNode || node.constructor === HashCollisionNode; } function mergeIntoNode(node, ownerID, shift, keyHash, entry) { if (node.keyHash === keyHash) { return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); } var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var newNode; var nodes = idx1 === idx2 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); } function createNodes(ownerID, entries, key, value) { if (!ownerID) { ownerID = new OwnerID(); } var node = new ValueNode(ownerID, hash(key), [key, value]); for (var ii = 0; ii < entries.length; ii++) { var entry = entries[ii]; node = node.update(ownerID, 0, undefined, entry[0], entry[1]); } return node; } function packNodes(ownerID, nodes, count, excluding) { var bitmap = 0; var packedII = 0; var packedNodes = new Array(count); for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { var node = nodes[ii]; if (node !== undefined && ii !== excluding) { bitmap |= bit; packedNodes[packedII++] = node; } } return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } function expandNodes(ownerID, nodes, bitmap, including, node) { var count = 0; var expandedNodes = new Array(SIZE); for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; } expandedNodes[including] = node; return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } function mergeIntoMapWith(map, merger, iterables) { var iters = []; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = KeyedIterable(value); if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } return mergeIntoCollectionWith(map, merger, iters); } function deepMerger(existing, value, key) { return existing && existing.mergeDeep && isIterable(value) ? existing.mergeDeep(value) : is(existing, value) ? existing : value; } function deepMergerWith(merger) { return function(existing, value, key) { if (existing && existing.mergeDeepWith && isIterable(value)) { return existing.mergeDeepWith(merger, value); } var nextValue = merger(existing, value, key); return is(existing, nextValue) ? existing : nextValue; }; } function mergeIntoCollectionWith(collection, merger, iters) { iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return collection; } if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { return collection.constructor(iters[0]); } return collection.withMutations(function(collection ) { var mergeIntoMap = merger ? function(value, key) { collection.update(key, NOT_SET, function(existing ) {return existing === NOT_SET ? value : merger(existing, value, key)} ); } : function(value, key) { collection.set(key, value); } for (var ii = 0; ii < iters.length; ii++) { iters[ii].forEach(mergeIntoMap); } }); } function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { var isNotSet = existing === NOT_SET; var step = keyPathIter.next(); if (step.done) { var existingValue = isNotSet ? notSetValue : existing; var newValue = updater(existingValue); return newValue === existingValue ? existing : newValue; } invariant( isNotSet || (existing && existing.set), 'invalid keyPath' ); var key = step.value; var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); var nextUpdated = updateInDeepMap( nextExisting, keyPathIter, notSetValue, updater ); return nextUpdated === nextExisting ? existing : nextUpdated === NOT_SET ? existing.remove(key) : (isNotSet ? emptyMap() : existing).set(key, nextUpdated); } function popCount(x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x = x + (x >> 8); x = x + (x >> 16); return x & 0x7f; } function setIn(array, idx, val, canEdit) { var newArray = canEdit ? array : arrCopy(array); newArray[idx] = val; return newArray; } function spliceIn(array, idx, val, canEdit) { var newLen = array.length + 1; if (canEdit && idx + 1 === newLen) { array[idx] = val; return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { newArray[ii] = val; after = -1; } else { newArray[ii] = array[ii + after]; } } return newArray; } function spliceOut(array, idx, canEdit) { var newLen = array.length - 1; if (canEdit && idx === newLen) { array.pop(); return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { after = 1; } newArray[ii] = array[ii + after]; } return newArray; } var MAX_ARRAY_MAP_SIZE = SIZE / 4; var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; createClass(List, IndexedCollection); // @pragma Construction function List(value) { var empty = emptyList(); if (value === null || value === undefined) { return empty; } if (isList(value)) { return value; } var iter = IndexedIterable(value); var size = iter.size; if (size === 0) { return empty; } assertNotInfinite(size); if (size > 0 && size < SIZE) { return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); } return empty.withMutations(function(list ) { list.setSize(size); iter.forEach(function(v, i) {return list.set(i, v)}); }); } List.of = function(/*...values*/) { return this(arguments); }; List.prototype.toString = function() { return this.__toString('List [', ']'); }; // @pragma Access List.prototype.get = function(index, notSetValue) { index = wrapIndex(this, index); if (index >= 0 && index < this.size) { index += this._origin; var node = listNodeFor(this, index); return node && node.array[index & MASK]; } return notSetValue; }; // @pragma Modification List.prototype.set = function(index, value) { return updateList(this, index, value); }; List.prototype.remove = function(index) { return !this.has(index) ? this : index === 0 ? this.shift() : index === this.size - 1 ? this.pop() : this.splice(index, 1); }; List.prototype.insert = function(index, value) { return this.splice(index, 0, value); }; List.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = this._origin = this._capacity = 0; this._level = SHIFT; this._root = this._tail = null; this.__hash = undefined; this.__altered = true; return this; } return emptyList(); }; List.prototype.push = function(/*...values*/) { var values = arguments; var oldSize = this.size; return this.withMutations(function(list ) { setListBounds(list, 0, oldSize + values.length); for (var ii = 0; ii < values.length; ii++) { list.set(oldSize + ii, values[ii]); } }); }; List.prototype.pop = function() { return setListBounds(this, 0, -1); }; List.prototype.unshift = function(/*...values*/) { var values = arguments; return this.withMutations(function(list ) { setListBounds(list, -values.length); for (var ii = 0; ii < values.length; ii++) { list.set(ii, values[ii]); } }); }; List.prototype.shift = function() { return setListBounds(this, 1); }; // @pragma Composition List.prototype.merge = function(/*...iters*/) { return mergeIntoListWith(this, undefined, arguments); }; List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, merger, iters); }; List.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoListWith(this, deepMerger, arguments); }; List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, deepMergerWith(merger), iters); }; List.prototype.setSize = function(size) { return setListBounds(this, 0, size); }; // @pragma Iteration List.prototype.slice = function(begin, end) { var size = this.size; if (wholeSlice(begin, end, size)) { return this; } return setListBounds( this, resolveBegin(begin, size), resolveEnd(end, size) ); }; List.prototype.__iterator = function(type, reverse) { var index = 0; var values = iterateList(this, reverse); return new Iterator(function() { var value = values(); return value === DONE ? iteratorDone() : iteratorValue(type, index++, value); }); }; List.prototype.__iterate = function(fn, reverse) { var index = 0; var values = iterateList(this, reverse); var value; while ((value = values()) !== DONE) { if (fn(value, index++, this) === false) { break; } } return index; }; List.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; return this; } return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); }; function isList(maybeList) { return !!(maybeList && maybeList[IS_LIST_SENTINEL]); } List.isList = isList; var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; var ListPrototype = List.prototype; ListPrototype[IS_LIST_SENTINEL] = true; ListPrototype[DELETE] = ListPrototype.remove; ListPrototype.setIn = MapPrototype.setIn; ListPrototype.deleteIn = ListPrototype.removeIn = MapPrototype.removeIn; ListPrototype.update = MapPrototype.update; ListPrototype.updateIn = MapPrototype.updateIn; ListPrototype.mergeIn = MapPrototype.mergeIn; ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; ListPrototype.withMutations = MapPrototype.withMutations; ListPrototype.asMutable = MapPrototype.asMutable; ListPrototype.asImmutable = MapPrototype.asImmutable; ListPrototype.wasAltered = MapPrototype.wasAltered; function VNode(array, ownerID) { this.array = array; this.ownerID = ownerID; } // TODO: seems like these methods are very similar VNode.prototype.removeBefore = function(ownerID, level, index) { if (index === level ? 1 << level : 0 || this.array.length === 0) { return this; } var originIndex = (index >>> level) & MASK; if (originIndex >= this.array.length) { return new VNode([], ownerID); } var removingFirst = originIndex === 0; var newChild; if (level > 0) { var oldChild = this.array[originIndex]; newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); if (newChild === oldChild && removingFirst) { return this; } } if (removingFirst && !newChild) { return this; } var editable = editableVNode(this, ownerID); if (!removingFirst) { for (var ii = 0; ii < originIndex; ii++) { editable.array[ii] = undefined; } } if (newChild) { editable.array[originIndex] = newChild; } return editable; }; VNode.prototype.removeAfter = function(ownerID, level, index) { if (index === (level ? 1 << level : 0) || this.array.length === 0) { return this; } var sizeIndex = ((index - 1) >>> level) & MASK; if (sizeIndex >= this.array.length) { return this; } var newChild; if (level > 0) { var oldChild = this.array[sizeIndex]; newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); if (newChild === oldChild && sizeIndex === this.array.length - 1) { return this; } } var editable = editableVNode(this, ownerID); editable.array.splice(sizeIndex + 1); if (newChild) { editable.array[sizeIndex] = newChild; } return editable; }; var DONE = {}; function iterateList(list, reverse) { var left = list._origin; var right = list._capacity; var tailPos = getTailOffset(right); var tail = list._tail; return iterateNodeOrLeaf(list._root, list._level, 0); function iterateNodeOrLeaf(node, level, offset) { return level === 0 ? iterateLeaf(node, offset) : iterateNode(node, level, offset); } function iterateLeaf(node, offset) { var array = offset === tailPos ? tail && tail.array : node && node.array; var from = offset > left ? 0 : left - offset; var to = right - offset; if (to > SIZE) { to = SIZE; } return function() { if (from === to) { return DONE; } var idx = reverse ? --to : from++; return array && array[idx]; }; } function iterateNode(node, level, offset) { var values; var array = node && node.array; var from = offset > left ? 0 : (left - offset) >> level; var to = ((right - offset) >> level) + 1; if (to > SIZE) { to = SIZE; } return function() { do { if (values) { var value = values(); if (value !== DONE) { return value; } values = null; } if (from === to) { return DONE; } var idx = reverse ? --to : from++; values = iterateNodeOrLeaf( array && array[idx], level - SHIFT, offset + (idx << level) ); } while (true); }; } } function makeList(origin, capacity, level, root, tail, ownerID, hash) { var list = Object.create(ListPrototype); list.size = capacity - origin; list._origin = origin; list._capacity = capacity; list._level = level; list._root = root; list._tail = tail; list.__ownerID = ownerID; list.__hash = hash; list.__altered = false; return list; } var EMPTY_LIST; function emptyList() { return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); } function updateList(list, index, value) { index = wrapIndex(list, index); if (index !== index) { return list; } if (index >= list.size || index < 0) { return list.withMutations(function(list ) { index < 0 ? setListBounds(list, index).set(0, value) : setListBounds(list, 0, index + 1).set(index, value) }); } index += list._origin; var newTail = list._tail; var newRoot = list._root; var didAlter = MakeRef(DID_ALTER); if (index >= getTailOffset(list._capacity)) { newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); } else { newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); } if (!didAlter.value) { return list; } if (list.__ownerID) { list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(list._origin, list._capacity, list._level, newRoot, newTail); } function updateVNode(node, ownerID, level, index, value, didAlter) { var idx = (index >>> level) & MASK; var nodeHas = node && idx < node.array.length; if (!nodeHas && value === undefined) { return node; } var newNode; if (level > 0) { var lowerNode = node && node.array[idx]; var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); if (newLowerNode === lowerNode) { return node; } newNode = editableVNode(node, ownerID); newNode.array[idx] = newLowerNode; return newNode; } if (nodeHas && node.array[idx] === value) { return node; } SetRef(didAlter); newNode = editableVNode(node, ownerID); if (value === undefined && idx === newNode.array.length - 1) { newNode.array.pop(); } else { newNode.array[idx] = value; } return newNode; } function editableVNode(node, ownerID) { if (ownerID && node && ownerID === node.ownerID) { return node; } return new VNode(node ? node.array.slice() : [], ownerID); } function listNodeFor(list, rawIndex) { if (rawIndex >= getTailOffset(list._capacity)) { return list._tail; } if (rawIndex < 1 << (list._level + SHIFT)) { var node = list._root; var level = list._level; while (node && level > 0) { node = node.array[(rawIndex >>> level) & MASK]; level -= SHIFT; } return node; } } function setListBounds(list, begin, end) { // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } var owner = list.__ownerID || new OwnerID(); var oldOrigin = list._origin; var oldCapacity = list._capacity; var newOrigin = oldOrigin + begin; var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; if (newOrigin === oldOrigin && newCapacity === oldCapacity) { return list; } // If it's going to end after it starts, it's empty. if (newOrigin >= newCapacity) { return list.clear(); } var newLevel = list._level; var newRoot = list._root; // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); newLevel += SHIFT; offsetShift += 1 << newLevel; } if (offsetShift) { newOrigin += offsetShift; oldOrigin += offsetShift; newCapacity += offsetShift; oldCapacity += offsetShift; } var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); newLevel += SHIFT; } // Locate or create the new tail. var oldTail = list._tail; var newTail = newTailOffset < oldTailOffset ? listNodeFor(list, newCapacity - 1) : newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; // Merge Tail into tree. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { newRoot = editableVNode(newRoot, owner); var node = newRoot; for (var level = newLevel; level > SHIFT; level -= SHIFT) { var idx = (oldTailOffset >>> level) & MASK; node = node.array[idx] = editableVNode(node.array[idx], owner); } node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } // If the size has been reduced, there's a chance the tail needs to be trimmed. if (newCapacity < oldCapacity) { newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } // If the new origin is within the tail, then we do not need a root. if (newOrigin >= newTailOffset) { newOrigin -= newTailOffset; newCapacity -= newTailOffset; newLevel = SHIFT; newRoot = null; newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); // Otherwise, if the root has been trimmed, garbage collect. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { offsetShift = 0; // Identify the new top root node of the subtree of the old root. while (newRoot) { var beginIndex = (newOrigin >>> newLevel) & MASK; if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { break; } if (beginIndex) { offsetShift += (1 << newLevel) * beginIndex; } newLevel -= SHIFT; newRoot = newRoot.array[beginIndex]; } // Trim the new sides of the new root. if (newRoot && newOrigin > oldOrigin) { newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } if (newRoot && newTailOffset < oldTailOffset) { newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); } if (offsetShift) { newOrigin -= offsetShift; newCapacity -= offsetShift; } } if (list.__ownerID) { list.size = newCapacity - newOrigin; list._origin = newOrigin; list._capacity = newCapacity; list._level = newLevel; list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); } function mergeIntoListWith(list, merger, iterables) { var iters = []; var maxSize = 0; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = IndexedIterable(value); if (iter.size > maxSize) { maxSize = iter.size; } if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } if (maxSize > list.size) { list = list.setSize(maxSize); } return mergeIntoCollectionWith(list, merger, iters); } function getTailOffset(size) { return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); } createClass(OrderedMap, Map); // @pragma Construction function OrderedMap(value) { return value === null || value === undefined ? emptyOrderedMap() : isOrderedMap(value) ? value : emptyOrderedMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } OrderedMap.of = function(/*...values*/) { return this(arguments); }; OrderedMap.prototype.toString = function() { return this.__toString('OrderedMap {', '}'); }; // @pragma Access OrderedMap.prototype.get = function(k, notSetValue) { var index = this._map.get(k); return index !== undefined ? this._list.get(index)[1] : notSetValue; }; // @pragma Modification OrderedMap.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._map.clear(); this._list.clear(); return this; } return emptyOrderedMap(); }; OrderedMap.prototype.set = function(k, v) { return updateOrderedMap(this, k, v); }; OrderedMap.prototype.remove = function(k) { return updateOrderedMap(this, k, NOT_SET); }; OrderedMap.prototype.wasAltered = function() { return this._map.wasAltered() || this._list.wasAltered(); }; OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._list.__iterate( function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, reverse ); }; OrderedMap.prototype.__iterator = function(type, reverse) { return this._list.fromEntrySeq().__iterator(type, reverse); }; OrderedMap.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); var newList = this._list.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; this._list = newList; return this; } return makeOrderedMap(newMap, newList, ownerID, this.__hash); }; function isOrderedMap(maybeOrderedMap) { return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } OrderedMap.isOrderedMap = isOrderedMap; OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; function makeOrderedMap(map, list, ownerID, hash) { var omap = Object.create(OrderedMap.prototype); omap.size = map ? map.size : 0; omap._map = map; omap._list = list; omap.__ownerID = ownerID; omap.__hash = hash; return omap; } var EMPTY_ORDERED_MAP; function emptyOrderedMap() { return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); } function updateOrderedMap(omap, k, v) { var map = omap._map; var list = omap._list; var i = map.get(k); var has = i !== undefined; var newMap; var newList; if (v === NOT_SET) { // removed if (!has) { return omap; } if (list.size >= SIZE && list.size >= map.size * 2) { newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); if (omap.__ownerID) { newMap.__ownerID = newList.__ownerID = omap.__ownerID; } } else { newMap = map.remove(k); newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); } } else { if (has) { if (v === list.get(i)[1]) { return omap; } newMap = map; newList = list.set(i, [k, v]); } else { newMap = map.set(k, list.size); newList = list.set(list.size, [k, v]); } } if (omap.__ownerID) { omap.size = newMap.size; omap._map = newMap; omap._list = newList; omap.__hash = undefined; return omap; } return makeOrderedMap(newMap, newList); } createClass(ToKeyedSequence, KeyedSeq); function ToKeyedSequence(indexed, useKeys) { this._iter = indexed; this._useKeys = useKeys; this.size = indexed.size; } ToKeyedSequence.prototype.get = function(key, notSetValue) { return this._iter.get(key, notSetValue); }; ToKeyedSequence.prototype.has = function(key) { return this._iter.has(key); }; ToKeyedSequence.prototype.valueSeq = function() { return this._iter.valueSeq(); }; ToKeyedSequence.prototype.reverse = function() {var this$0 = this; var reversedSequence = reverseFactory(this, true); if (!this._useKeys) { reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; } return reversedSequence; }; ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; var mappedSequence = mapFactory(this, mapper, context); if (!this._useKeys) { mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; } return mappedSequence; }; ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var ii; return this._iter.__iterate( this._useKeys ? function(v, k) {return fn(v, k, this$0)} : ((ii = reverse ? resolveSize(this) : 0), function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), reverse ); }; ToKeyedSequence.prototype.__iterator = function(type, reverse) { if (this._useKeys) { return this._iter.__iterator(type, reverse); } var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var ii = reverse ? resolveSize(this) : 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, reverse ? --ii : ii++, step.value, step); }); }; ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; createClass(ToIndexedSequence, IndexedSeq); function ToIndexedSequence(iter) { this._iter = iter; this.size = iter.size; } ToIndexedSequence.prototype.includes = function(value) { return this._iter.includes(value); }; ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); }; ToIndexedSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value, step) }); }; createClass(ToSetSequence, SetSeq); function ToSetSequence(iter) { this._iter = iter; this.size = iter.size; } ToSetSequence.prototype.has = function(key) { return this._iter.includes(key); }; ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); }; ToSetSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, step.value, step.value, step); }); }; createClass(FromEntriesSequence, KeyedSeq); function FromEntriesSequence(entries) { this._iter = entries; this.size = entries.size; } FromEntriesSequence.prototype.entrySeq = function() { return this._iter.toSeq(); }; FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(entry ) { // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return fn( indexedIterable ? entry.get(1) : entry[1], indexedIterable ? entry.get(0) : entry[0], this$0 ); } }, reverse); }; FromEntriesSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return iteratorValue( type, indexedIterable ? entry.get(0) : entry[0], indexedIterable ? entry.get(1) : entry[1], step ); } } }); }; ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; function flipFactory(iterable) { var flipSequence = makeSequence(iterable); flipSequence._iter = iterable; flipSequence.size = iterable.size; flipSequence.flip = function() {return iterable}; flipSequence.reverse = function () { var reversedSequence = iterable.reverse.apply(this); // super.reverse() reversedSequence.flip = function() {return iterable.reverse()}; return reversedSequence; }; flipSequence.has = function(key ) {return iterable.includes(key)}; flipSequence.includes = function(key ) {return iterable.has(key)}; flipSequence.cacheResult = cacheResultThrough; flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); } flipSequence.__iteratorUncached = function(type, reverse) { if (type === ITERATE_ENTRIES) { var iterator = iterable.__iterator(type, reverse); return new Iterator(function() { var step = iterator.next(); if (!step.done) { var k = step.value[0]; step.value[0] = step.value[1]; step.value[1] = k; } return step; }); } return iterable.__iterator( type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse ); } return flipSequence; } function mapFactory(iterable, mapper, context) { var mappedSequence = makeSequence(iterable); mappedSequence.size = iterable.size; mappedSequence.has = function(key ) {return iterable.has(key)}; mappedSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v === NOT_SET ? notSetValue : mapper.call(context, v, key, iterable); }; mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate( function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, reverse ); } mappedSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); return new Iterator(function() { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; return iteratorValue( type, key, mapper.call(context, entry[1], key, iterable), step ); }); } return mappedSequence; } function reverseFactory(iterable, useKeys) { var reversedSequence = makeSequence(iterable); reversedSequence._iter = iterable; reversedSequence.size = iterable.size; reversedSequence.reverse = function() {return iterable}; if (iterable.flip) { reversedSequence.flip = function () { var flipSequence = flipFactory(iterable); flipSequence.reverse = function() {return iterable.flip()}; return flipSequence; }; } reversedSequence.get = function(key, notSetValue) {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; reversedSequence.has = function(key ) {return iterable.has(useKeys ? key : -1 - key)}; reversedSequence.includes = function(value ) {return iterable.includes(value)}; reversedSequence.cacheResult = cacheResultThrough; reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); }; reversedSequence.__iterator = function(type, reverse) {return iterable.__iterator(type, !reverse)}; return reversedSequence; } function filterFactory(iterable, predicate, context, useKeys) { var filterSequence = makeSequence(iterable); if (useKeys) { filterSequence.has = function(key ) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && !!predicate.call(context, v, key, iterable); }; filterSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && predicate.call(context, v, key, iterable) ? v : notSetValue; }; } filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }, reverse); return iterations; }; filterSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterations = 0; return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; var value = entry[1]; if (predicate.call(context, value, key, iterable)) { return iteratorValue(type, useKeys ? key : iterations++, value, step); } } }); } return filterSequence; } function countByFactory(iterable, grouper, context) { var groups = Map().asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), 0, function(a ) {return a + 1} ); }); return groups.asImmutable(); } function groupByFactory(iterable, grouper, context) { var isKeyedIter = isKeyed(iterable); var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} ); }); var coerce = iterableClass(iterable); return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); } function sliceFactory(iterable, begin, end, useKeys) { var originalSize = iterable.size; // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } if (wholeSlice(begin, end, originalSize)) { return iterable; } var resolvedBegin = resolveBegin(begin, originalSize); var resolvedEnd = resolveEnd(end, originalSize); // begin or end will be NaN if they were provided as negative numbers and // this iterable's size is unknown. In that case, cache first so there is // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); } // Note: resolvedEnd is undefined when the original sequence's length is // unknown and this slice did not supply an end and should contain all // elements after resolvedBegin. // In that case, resolvedSize will be NaN and sliceSize will remain undefined. var resolvedSize = resolvedEnd - resolvedBegin; var sliceSize; if (resolvedSize === resolvedSize) { sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(iterable); // If iterable.size is undefined, the size of the realized sliceSeq is // unknown at this point unless the number of items to slice is 0 sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; if (!useKeys && isSeq(iterable) && sliceSize >= 0) { sliceSeq.get = function (index, notSetValue) { index = wrapIndex(this, index); return index >= 0 && index < sliceSize ? iterable.get(index + resolvedBegin, notSetValue) : notSetValue; } } sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; if (sliceSize === 0) { return 0; } if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var skipped = 0; var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k) { if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0) !== false && iterations !== sliceSize; } }); return iterations; }; sliceSeq.__iteratorUncached = function(type, reverse) { if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new Iterator(function() { while (skipped++ < resolvedBegin) { iterator.next(); } if (++iterations > sliceSize) { return iteratorDone(); } var step = iterator.next(); if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations - 1, undefined, step); } else { return iteratorValue(type, iterations - 1, step.value[1], step); } }); } return sliceSeq; } function takeWhileFactory(iterable, predicate, context) { var takeSequence = makeSequence(iterable); takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; iterable.__iterate(function(v, k, c) {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} ); return iterations; }; takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterating = true; return new Iterator(function() { if (!iterating) { return iteratorDone(); } var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var k = entry[0]; var v = entry[1]; if (!predicate.call(context, v, k, this$0)) { iterating = false; return iteratorDone(); } return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return takeSequence; } function skipWhileFactory(iterable, predicate, context, useKeys) { var skipSequence = makeSequence(iterable); skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k, c) { if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }); return iterations; }; skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var skipping = true; var iterations = 0; return new Iterator(function() { var step, k, v; do { step = iterator.next(); if (step.done) { if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations++, undefined, step); } else { return iteratorValue(type, iterations++, step.value[1], step); } } var entry = step.value; k = entry[0]; v = entry[1]; skipping && (skipping = predicate.call(context, v, k, this$0)); } while (skipping); return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return skipSequence; } function concatFactory(iterable, values) { var isKeyedIterable = isKeyed(iterable); var iters = [iterable].concat(values).map(function(v ) { if (!isIterable(v)) { v = isKeyedIterable ? keyedSeqFromValue(v) : indexedSeqFromValue(Array.isArray(v) ? v : [v]); } else if (isKeyedIterable) { v = KeyedIterable(v); } return v; }).filter(function(v ) {return v.size !== 0}); if (iters.length === 0) { return iterable; } if (iters.length === 1) { var singleton = iters[0]; if (singleton === iterable || isKeyedIterable && isKeyed(singleton) || isIndexed(iterable) && isIndexed(singleton)) { return singleton; } } var concatSeq = new ArraySeq(iters); if (isKeyedIterable) { concatSeq = concatSeq.toKeyedSeq(); } else if (!isIndexed(iterable)) { concatSeq = concatSeq.toSetSeq(); } concatSeq = concatSeq.flatten(true); concatSeq.size = iters.reduce( function(sum, seq) { if (sum !== undefined) { var size = seq.size; if (size !== undefined) { return sum + size; } } }, 0 ); return concatSeq; } function flattenFactory(iterable, depth, useKeys) { var flatSequence = makeSequence(iterable); flatSequence.__iterateUncached = function(fn, reverse) { var iterations = 0; var stopped = false; function flatDeep(iter, currentDepth) {var this$0 = this; iter.__iterate(function(v, k) { if ((!depth || currentDepth < depth) && isIterable(v)) { flatDeep(v, currentDepth + 1); } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { stopped = true; } return !stopped; }, reverse); } flatDeep(iterable, 0); return iterations; } flatSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(type, reverse); var stack = []; var iterations = 0; return new Iterator(function() { while (iterator) { var step = iterator.next(); if (step.done !== false) { iterator = stack.pop(); continue; } var v = step.value; if (type === ITERATE_ENTRIES) { v = v[1]; } if ((!depth || stack.length < depth) && isIterable(v)) { stack.push(iterator); iterator = v.__iterator(type, reverse); } else { return useKeys ? step : iteratorValue(type, iterations++, v, step); } } return iteratorDone(); }); } return flatSequence; } function flatMapFactory(iterable, mapper, context) { var coerce = iterableClass(iterable); return iterable.toSeq().map( function(v, k) {return coerce(mapper.call(context, v, k, iterable))} ).flatten(true); } function interposeFactory(iterable, separator) { var interposedSequence = makeSequence(iterable); interposedSequence.size = iterable.size && iterable.size * 2 -1; interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k) {return (!iterations || fn(separator, iterations++, this$0) !== false) && fn(v, iterations++, this$0) !== false}, reverse ); return iterations; }; interposedSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(ITERATE_VALUES, reverse); var iterations = 0; var step; return new Iterator(function() { if (!step || iterations % 2) { step = iterator.next(); if (step.done) { return step; } } return iterations % 2 ? iteratorValue(type, iterations++, separator) : iteratorValue(type, iterations++, step.value, step); }); }; return interposedSequence; } function sortFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } var isKeyedIterable = isKeyed(iterable); var index = 0; var entries = iterable.toSeq().map( function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} ).toArray(); entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( isKeyedIterable ? function(v, i) { entries[i].length = 2; } : function(v, i) { entries[i] = v[1]; } ); return isKeyedIterable ? KeyedSeq(entries) : isIndexed(iterable) ? IndexedSeq(entries) : SetSeq(entries); } function maxFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } if (mapper) { var entry = iterable.toSeq() .map(function(v, k) {return [v, mapper(v, k, iterable)]}) .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); return entry && entry[0]; } else { return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); } } function maxCompare(comparator, a, b) { var comp = comparator(b, a); // b is considered the new max if the comparator declares them equal, but // they are not equal and b is in fact a nullish value. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; } function zipWithFactory(keyIter, zipper, iters) { var zipSequence = makeSequence(keyIter); zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); // Note: this a generic base implementation of __iterate in terms of // __iterator which may be more generically useful in the future. zipSequence.__iterate = function(fn, reverse) { /* generic: var iterator = this.__iterator(ITERATE_ENTRIES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { iterations++; if (fn(step.value[1], step.value[0], this) === false) { break; } } return iterations; */ // indexed: var iterator = this.__iterator(ITERATE_VALUES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } return iterations; }; zipSequence.__iteratorUncached = function(type, reverse) { var iterators = iters.map(function(i ) {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} ); var iterations = 0; var isDone = false; return new Iterator(function() { var steps; if (!isDone) { steps = iterators.map(function(i ) {return i.next()}); isDone = steps.some(function(s ) {return s.done}); } if (isDone) { return iteratorDone(); } return iteratorValue( type, iterations++, zipper.apply(null, steps.map(function(s ) {return s.value})) ); }); }; return zipSequence } // #pragma Helper Functions function reify(iter, seq) { return isSeq(iter) ? seq : iter.constructor(seq); } function validateEntry(entry) { if (entry !== Object(entry)) { throw new TypeError('Expected [K, V] tuple: ' + entry); } } function resolveSize(iter) { assertNotInfinite(iter.size); return ensureSize(iter); } function iterableClass(iterable) { return isKeyed(iterable) ? KeyedIterable : isIndexed(iterable) ? IndexedIterable : SetIterable; } function makeSequence(iterable) { return Object.create( ( isKeyed(iterable) ? KeyedSeq : isIndexed(iterable) ? IndexedSeq : SetSeq ).prototype ); } function cacheResultThrough() { if (this._iter.cacheResult) { this._iter.cacheResult(); this.size = this._iter.size; return this; } else { return Seq.prototype.cacheResult.call(this); } } function defaultComparator(a, b) { return a > b ? 1 : a < b ? -1 : 0; } function forceIterator(keyPath) { var iter = getIterator(keyPath); if (!iter) { // Array might not be iterable in this environment, so we need a fallback // to our wrapped type. if (!isArrayLike(keyPath)) { throw new TypeError('Expected iterable or array-like: ' + keyPath); } iter = getIterator(Iterable(keyPath)); } return iter; } createClass(Record, KeyedCollection); function Record(defaultValues, name) { var hasInitialized; var RecordType = function Record(values) { if (values instanceof RecordType) { return values; } if (!(this instanceof RecordType)) { return new RecordType(values); } if (!hasInitialized) { hasInitialized = true; var keys = Object.keys(defaultValues); setProps(RecordTypePrototype, keys); RecordTypePrototype.size = keys.length; RecordTypePrototype._name = name; RecordTypePrototype._keys = keys; RecordTypePrototype._defaultValues = defaultValues; } this._map = Map(values); }; var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); RecordTypePrototype.constructor = RecordType; return RecordType; } Record.prototype.toString = function() { return this.__toString(recordName(this) + ' {', '}'); }; // @pragma Access Record.prototype.has = function(k) { return this._defaultValues.hasOwnProperty(k); }; Record.prototype.get = function(k, notSetValue) { if (!this.has(k)) { return notSetValue; } var defaultVal = this._defaultValues[k]; return this._map ? this._map.get(k, defaultVal) : defaultVal; }; // @pragma Modification Record.prototype.clear = function() { if (this.__ownerID) { this._map && this._map.clear(); return this; } var RecordType = this.constructor; return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); }; Record.prototype.set = function(k, v) { if (!this.has(k)) { throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); } var newMap = this._map && this._map.set(k, v); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.remove = function(k) { if (!this.has(k)) { return this; } var newMap = this._map && this._map.remove(k); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.wasAltered = function() { return this._map.wasAltered(); }; Record.prototype.__iterator = function(type, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); }; Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); }; Record.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map && this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return makeRecord(this, newMap, ownerID); }; var RecordPrototype = Record.prototype; RecordPrototype[DELETE] = RecordPrototype.remove; RecordPrototype.deleteIn = RecordPrototype.removeIn = MapPrototype.removeIn; RecordPrototype.merge = MapPrototype.merge; RecordPrototype.mergeWith = MapPrototype.mergeWith; RecordPrototype.mergeIn = MapPrototype.mergeIn; RecordPrototype.mergeDeep = MapPrototype.mergeDeep; RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; RecordPrototype.setIn = MapPrototype.setIn; RecordPrototype.update = MapPrototype.update; RecordPrototype.updateIn = MapPrototype.updateIn; RecordPrototype.withMutations = MapPrototype.withMutations; RecordPrototype.asMutable = MapPrototype.asMutable; RecordPrototype.asImmutable = MapPrototype.asImmutable; function makeRecord(likeRecord, map, ownerID) { var record = Object.create(Object.getPrototypeOf(likeRecord)); record._map = map; record.__ownerID = ownerID; return record; } function recordName(record) { return record._name || record.constructor.name || 'Record'; } function setProps(prototype, names) { try { names.forEach(setProp.bind(undefined, prototype)); } catch (error) { // Object.defineProperty failed. Probably IE8. } } function setProp(prototype, name) { Object.defineProperty(prototype, name, { get: function() { return this.get(name); }, set: function(value) { invariant(this.__ownerID, 'Cannot set on an immutable record.'); this.set(name, value); } }); } createClass(Set, SetCollection); // @pragma Construction function Set(value) { return value === null || value === undefined ? emptySet() : isSet(value) && !isOrdered(value) ? value : emptySet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } Set.of = function(/*...values*/) { return this(arguments); }; Set.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; Set.prototype.toString = function() { return this.__toString('Set {', '}'); }; // @pragma Access Set.prototype.has = function(value) { return this._map.has(value); }; // @pragma Modification Set.prototype.add = function(value) { return updateSet(this, this._map.set(value, true)); }; Set.prototype.remove = function(value) { return updateSet(this, this._map.remove(value)); }; Set.prototype.clear = function() { return updateSet(this, this._map.clear()); }; // @pragma Composition Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && iters.length === 1) { return this.constructor(iters[0]); } return this.withMutations(function(set ) { for (var ii = 0; ii < iters.length; ii++) { SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); } }); }; Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (!iters.every(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (iters.some(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.merge = function() { return this.union.apply(this, arguments); }; Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return this.union.apply(this, iters); }; Set.prototype.sort = function(comparator) { // Late binding return OrderedSet(sortFactory(this, comparator)); }; Set.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedSet(sortFactory(this, comparator, mapper)); }; Set.prototype.wasAltered = function() { return this._map.wasAltered(); }; Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); }; Set.prototype.__iterator = function(type, reverse) { return this._map.map(function(_, k) {return k}).__iterator(type, reverse); }; Set.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return this.__make(newMap, ownerID); }; function isSet(maybeSet) { return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); } Set.isSet = isSet; var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; var SetPrototype = Set.prototype; SetPrototype[IS_SET_SENTINEL] = true; SetPrototype[DELETE] = SetPrototype.remove; SetPrototype.mergeDeep = SetPrototype.merge; SetPrototype.mergeDeepWith = SetPrototype.mergeWith; SetPrototype.withMutations = MapPrototype.withMutations; SetPrototype.asMutable = MapPrototype.asMutable; SetPrototype.asImmutable = MapPrototype.asImmutable; SetPrototype.__empty = emptySet; SetPrototype.__make = makeSet; function updateSet(set, newMap) { if (set.__ownerID) { set.size = newMap.size; set._map = newMap; return set; } return newMap === set._map ? set : newMap.size === 0 ? set.__empty() : set.__make(newMap); } function makeSet(map, ownerID) { var set = Object.create(SetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_SET; function emptySet() { return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); } createClass(OrderedSet, Set); // @pragma Construction function OrderedSet(value) { return value === null || value === undefined ? emptyOrderedSet() : isOrderedSet(value) ? value : emptyOrderedSet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } OrderedSet.of = function(/*...values*/) { return this(arguments); }; OrderedSet.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; OrderedSet.prototype.toString = function() { return this.__toString('OrderedSet {', '}'); }; function isOrderedSet(maybeOrderedSet) { return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } OrderedSet.isOrderedSet = isOrderedSet; var OrderedSetPrototype = OrderedSet.prototype; OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; OrderedSetPrototype.__empty = emptyOrderedSet; OrderedSetPrototype.__make = makeOrderedSet; function makeOrderedSet(map, ownerID) { var set = Object.create(OrderedSetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_ORDERED_SET; function emptyOrderedSet() { return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); } createClass(Stack, IndexedCollection); // @pragma Construction function Stack(value) { return value === null || value === undefined ? emptyStack() : isStack(value) ? value : emptyStack().unshiftAll(value); } Stack.of = function(/*...values*/) { return this(arguments); }; Stack.prototype.toString = function() { return this.__toString('Stack [', ']'); }; // @pragma Access Stack.prototype.get = function(index, notSetValue) { var head = this._head; index = wrapIndex(this, index); while (head && index--) { head = head.next; } return head ? head.value : notSetValue; }; Stack.prototype.peek = function() { return this._head && this._head.value; }; // @pragma Modification Stack.prototype.push = function(/*...values*/) { if (arguments.length === 0) { return this; } var newSize = this.size + arguments.length; var head = this._head; for (var ii = arguments.length - 1; ii >= 0; ii--) { head = { value: arguments[ii], next: head }; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pushAll = function(iter) { iter = IndexedIterable(iter); if (iter.size === 0) { return this; } assertNotInfinite(iter.size); var newSize = this.size; var head = this._head; iter.reverse().forEach(function(value ) { newSize++; head = { value: value, next: head }; }); if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pop = function() { return this.slice(1); }; Stack.prototype.unshift = function(/*...values*/) { return this.push.apply(this, arguments); }; Stack.prototype.unshiftAll = function(iter) { return this.pushAll(iter); }; Stack.prototype.shift = function() { return this.pop.apply(this, arguments); }; Stack.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._head = undefined; this.__hash = undefined; this.__altered = true; return this; } return emptyStack(); }; Stack.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } var resolvedBegin = resolveBegin(begin, this.size); var resolvedEnd = resolveEnd(end, this.size); if (resolvedEnd !== this.size) { // super.slice(begin, end); return IndexedCollection.prototype.slice.call(this, begin, end); } var newSize = this.size - resolvedBegin; var head = this._head; while (resolvedBegin--) { head = head.next; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; // @pragma Mutability Stack.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeStack(this.size, this._head, ownerID, this.__hash); }; // @pragma Iteration Stack.prototype.__iterate = function(fn, reverse) { if (reverse) { return this.reverse().__iterate(fn); } var iterations = 0; var node = this._head; while (node) { if (fn(node.value, iterations++, this) === false) { break; } node = node.next; } return iterations; }; Stack.prototype.__iterator = function(type, reverse) { if (reverse) { return this.reverse().__iterator(type); } var iterations = 0; var node = this._head; return new Iterator(function() { if (node) { var value = node.value; node = node.next; return iteratorValue(type, iterations++, value); } return iteratorDone(); }); }; function isStack(maybeStack) { return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); } Stack.isStack = isStack; var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; var StackPrototype = Stack.prototype; StackPrototype[IS_STACK_SENTINEL] = true; StackPrototype.withMutations = MapPrototype.withMutations; StackPrototype.asMutable = MapPrototype.asMutable; StackPrototype.asImmutable = MapPrototype.asImmutable; StackPrototype.wasAltered = MapPrototype.wasAltered; function makeStack(size, head, ownerID, hash) { var map = Object.create(StackPrototype); map.size = size; map._head = head; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_STACK; function emptyStack() { return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); } /** * Contributes additional methods to a constructor */ function mixin(ctor, methods) { var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor; } Iterable.Iterator = Iterator; mixin(Iterable, { // ### Conversion to other types toArray: function() { assertNotInfinite(this.size); var array = new Array(this.size || 0); this.valueSeq().__iterate(function(v, i) { array[i] = v; }); return array; }, toIndexedSeq: function() { return new ToIndexedSequence(this); }, toJS: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} ).__toJS(); }, toJSON: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} ).__toJS(); }, toKeyedSeq: function() { return new ToKeyedSequence(this, true); }, toMap: function() { // Use Late Binding here to solve the circular dependency. return Map(this.toKeyedSeq()); }, toObject: function() { assertNotInfinite(this.size); var object = {}; this.__iterate(function(v, k) { object[k] = v; }); return object; }, toOrderedMap: function() { // Use Late Binding here to solve the circular dependency. return OrderedMap(this.toKeyedSeq()); }, toOrderedSet: function() { // Use Late Binding here to solve the circular dependency. return OrderedSet(isKeyed(this) ? this.valueSeq() : this); }, toSet: function() { // Use Late Binding here to solve the circular dependency. return Set(isKeyed(this) ? this.valueSeq() : this); }, toSetSeq: function() { return new ToSetSequence(this); }, toSeq: function() { return isIndexed(this) ? this.toIndexedSeq() : isKeyed(this) ? this.toKeyedSeq() : this.toSetSeq(); }, toStack: function() { // Use Late Binding here to solve the circular dependency. return Stack(isKeyed(this) ? this.valueSeq() : this); }, toList: function() { // Use Late Binding here to solve the circular dependency. return List(isKeyed(this) ? this.valueSeq() : this); }, // ### Common JavaScript methods and properties toString: function() { return '[Iterable]'; }, __toString: function(head, tail) { if (this.size === 0) { return head + tail; } return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; }, // ### ES6 Collection methods (ES6 Array and Map) concat: function() {var values = SLICE$0.call(arguments, 0); return reify(this, concatFactory(this, values)); }, includes: function(searchValue) { return this.some(function(value ) {return is(value, searchValue)}); }, entries: function() { return this.__iterator(ITERATE_ENTRIES); }, every: function(predicate, context) { assertNotInfinite(this.size); var returnValue = true; this.__iterate(function(v, k, c) { if (!predicate.call(context, v, k, c)) { returnValue = false; return false; } }); return returnValue; }, filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, true)); }, find: function(predicate, context, notSetValue) { var entry = this.findEntry(predicate, context); return entry ? entry[1] : notSetValue; }, findEntry: function(predicate, context) { var found; this.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { found = [k, v]; return false; } }); return found; }, findLastEntry: function(predicate, context) { return this.toSeq().reverse().findEntry(predicate, context); }, forEach: function(sideEffect, context) { assertNotInfinite(this.size); return this.__iterate(context ? sideEffect.bind(context) : sideEffect); }, join: function(separator) { assertNotInfinite(this.size); separator = separator !== undefined ? '' + separator : ','; var joined = ''; var isFirst = true; this.__iterate(function(v ) { isFirst ? (isFirst = false) : (joined += separator); joined += v !== null && v !== undefined ? v.toString() : ''; }); return joined; }, keys: function() { return this.__iterator(ITERATE_KEYS); }, map: function(mapper, context) { return reify(this, mapFactory(this, mapper, context)); }, reduce: function(reducer, initialReduction, context) { assertNotInfinite(this.size); var reduction; var useFirst; if (arguments.length < 2) { useFirst = true; } else { reduction = initialReduction; } this.__iterate(function(v, k, c) { if (useFirst) { useFirst = false; reduction = v; } else { reduction = reducer.call(context, reduction, v, k, c); } }); return reduction; }, reduceRight: function(reducer, initialReduction, context) { var reversed = this.toKeyedSeq().reverse(); return reversed.reduce.apply(reversed, arguments); }, reverse: function() { return reify(this, reverseFactory(this, true)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, true)); }, some: function(predicate, context) { return !this.every(not(predicate), context); }, sort: function(comparator) { return reify(this, sortFactory(this, comparator)); }, values: function() { return this.__iterator(ITERATE_VALUES); }, // ### More sequential methods butLast: function() { return this.slice(0, -1); }, isEmpty: function() { return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); }, count: function(predicate, context) { return ensureSize( predicate ? this.toSeq().filter(predicate, context) : this ); }, countBy: function(grouper, context) { return countByFactory(this, grouper, context); }, equals: function(other) { return deepEqual(this, other); }, entrySeq: function() { var iterable = this; if (iterable._cache) { // We cache as an entries array, so we can just return the cache! return new ArraySeq(iterable._cache); } var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; return entriesSequence; }, filterNot: function(predicate, context) { return this.filter(not(predicate), context); }, findLast: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); }, first: function() { return this.find(returnTrue); }, flatMap: function(mapper, context) { return reify(this, flatMapFactory(this, mapper, context)); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, true)); }, fromEntrySeq: function() { return new FromEntriesSequence(this); }, get: function(searchKey, notSetValue) { return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); }, getIn: function(searchKeyPath, notSetValue) { var nested = this; // Note: in an ES6 environment, we would prefer: // for (var key of searchKeyPath) { var iter = forceIterator(searchKeyPath); var step; while (!(step = iter.next()).done) { var key = step.value; nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; if (nested === NOT_SET) { return notSetValue; } } return nested; }, groupBy: function(grouper, context) { return groupByFactory(this, grouper, context); }, has: function(searchKey) { return this.get(searchKey, NOT_SET) !== NOT_SET; }, hasIn: function(searchKeyPath) { return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; }, isSubset: function(iter) { iter = typeof iter.includes === 'function' ? iter : Iterable(iter); return this.every(function(value ) {return iter.includes(value)}); }, isSuperset: function(iter) { iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); return iter.isSubset(this); }, keySeq: function() { return this.toSeq().map(keyMapper).toIndexedSeq(); }, last: function() { return this.toSeq().reverse().first(); }, max: function(comparator) { return maxFactory(this, comparator); }, maxBy: function(mapper, comparator) { return maxFactory(this, comparator, mapper); }, min: function(comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); }, minBy: function(mapper, comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); }, rest: function() { return this.slice(1); }, skip: function(amount) { return this.slice(Math.max(0, amount)); }, skipLast: function(amount) { return reify(this, this.toSeq().reverse().skip(amount).reverse()); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, true)); }, skipUntil: function(predicate, context) { return this.skipWhile(not(predicate), context); }, sortBy: function(mapper, comparator) { return reify(this, sortFactory(this, comparator, mapper)); }, take: function(amount) { return this.slice(0, Math.max(0, amount)); }, takeLast: function(amount) { return reify(this, this.toSeq().reverse().take(amount).reverse()); }, takeWhile: function(predicate, context) { return reify(this, takeWhileFactory(this, predicate, context)); }, takeUntil: function(predicate, context) { return this.takeWhile(not(predicate), context); }, valueSeq: function() { return this.toIndexedSeq(); }, // ### Hashable Object hashCode: function() { return this.__hash || (this.__hash = hashIterable(this)); } // ### Internal // abstract __iterate(fn, reverse) // abstract __iterator(type, reverse) }); // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; var IterablePrototype = Iterable.prototype; IterablePrototype[IS_ITERABLE_SENTINEL] = true; IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; IterablePrototype.__toJS = IterablePrototype.toArray; IterablePrototype.__toStringMapper = quoteString; IterablePrototype.inspect = IterablePrototype.toSource = function() { return this.toString(); }; IterablePrototype.chain = IterablePrototype.flatMap; IterablePrototype.contains = IterablePrototype.includes; // Temporary warning about using length (function () { try { Object.defineProperty(IterablePrototype, 'length', { get: function () { if (!Iterable.noLengthWarning) { var stack; try { throw new Error(); } catch (error) { stack = error.stack; } if (stack.indexOf('_wrapObject') === -1) { console && console.warn && console.warn( 'iterable.length has been deprecated, '+ 'use iterable.size or iterable.count(). '+ 'This warning will become a silent error in a future version. ' + stack ); return this.size; } } } }); } catch (e) {} })(); mixin(KeyedIterable, { // ### More sequential methods flip: function() { return reify(this, flipFactory(this)); }, findKey: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLastKey: function(predicate, context) { return this.toSeq().reverse().findKey(predicate, context); }, keyOf: function(searchValue) { return this.findKey(function(value ) {return is(value, searchValue)}); }, lastKeyOf: function(searchValue) { return this.findLastKey(function(value ) {return is(value, searchValue)}); }, mapEntries: function(mapper, context) {var this$0 = this; var iterations = 0; return reify(this, this.toSeq().map( function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} ).fromEntrySeq() ); }, mapKeys: function(mapper, context) {var this$0 = this; return reify(this, this.toSeq().flip().map( function(k, v) {return mapper.call(context, k, v, this$0)} ).flip() ); } }); var KeyedIterablePrototype = KeyedIterable.prototype; KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; KeyedIterablePrototype.__toJS = IterablePrototype.toObject; KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; mixin(IndexedIterable, { // ### Conversion to other types toKeyedSeq: function() { return new ToKeyedSequence(this, false); }, // ### ES6 Collection methods (ES6 Array and Map) filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, false)); }, findIndex: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry ? entry[0] : -1; }, indexOf: function(searchValue) { var key = this.toKeyedSeq().keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function(searchValue) { var key = this.toKeyedSeq().reverse().keyOf(searchValue); return key === undefined ? -1 : key; // var index = // return this.toSeq().reverse().indexOf(searchValue); }, reverse: function() { return reify(this, reverseFactory(this, false)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, false)); }, splice: function(index, removeNum /*, ...values*/) { var numArgs = arguments.length; removeNum = Math.max(removeNum | 0, 0); if (numArgs === 0 || (numArgs === 2 && !removeNum)) { return this; } // If index is negative, it should resolve relative to the size of the // collection. However size may be expensive to compute if not cached, so // only call count() if the number is in fact negative. index = resolveBegin(index, index < 0 ? this.count() : this.size); var spliced = this.slice(0, index); return reify( this, numArgs === 1 ? spliced : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) ); }, // ### More collection methods findLastIndex: function(predicate, context) { var key = this.toKeyedSeq().findLastKey(predicate, context); return key === undefined ? -1 : key; }, first: function() { return this.get(0); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, false)); }, get: function(index, notSetValue) { index = wrapIndex(this, index); return (index < 0 || (this.size === Infinity || (this.size !== undefined && index > this.size))) ? notSetValue : this.find(function(_, key) {return key === index}, undefined, notSetValue); }, has: function(index) { index = wrapIndex(this, index); return index >= 0 && (this.size !== undefined ? this.size === Infinity || index < this.size : this.indexOf(index) !== -1 ); }, interpose: function(separator) { return reify(this, interposeFactory(this, separator)); }, interleave: function(/*...iterables*/) { var iterables = [this].concat(arrCopy(arguments)); var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); var interleaved = zipped.flatten(true); if (zipped.size) { interleaved.size = zipped.size * iterables.length; } return reify(this, interleaved); }, last: function() { return this.get(-1); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, false)); }, zip: function(/*, ...iterables */) { var iterables = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, iterables)); }, zipWith: function(zipper/*, ...iterables */) { var iterables = arrCopy(arguments); iterables[0] = this; return reify(this, zipWithFactory(this, zipper, iterables)); } }); IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; mixin(SetIterable, { // ### ES6 Collection methods (ES6 Array and Map) get: function(value, notSetValue) { return this.has(value) ? value : notSetValue; }, includes: function(value) { return this.has(value); }, // ### More sequential methods keySeq: function() { return this.valueSeq(); } }); SetIterable.prototype.has = IterablePrototype.includes; // Mixin subclasses mixin(KeyedSeq, KeyedIterable.prototype); mixin(IndexedSeq, IndexedIterable.prototype); mixin(SetSeq, SetIterable.prototype); mixin(KeyedCollection, KeyedIterable.prototype); mixin(IndexedCollection, IndexedIterable.prototype); mixin(SetCollection, SetIterable.prototype); // #pragma Helper functions function keyMapper(v, k) { return k; } function entryMapper(v, k) { return [k, v]; } function not(predicate) { return function() { return !predicate.apply(this, arguments); } } function neg(predicate) { return function() { return -predicate.apply(this, arguments); } } function quoteString(value) { return typeof value === 'string' ? JSON.stringify(value) : value; } function defaultZipper() { return arrCopy(arguments); } function defaultNegComparator(a, b) { return a < b ? 1 : a > b ? -1 : 0; } function hashIterable(iterable) { if (iterable.size === Infinity) { return 0; } var ordered = isOrdered(iterable); var keyed = isKeyed(iterable); var h = ordered ? 1 : 0; var size = iterable.__iterate( keyed ? ordered ? function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : ordered ? function(v ) { h = 31 * h + hash(v) | 0; } : function(v ) { h = h + hash(v) | 0; } ); return murmurHashOfSize(size, h); } function murmurHashOfSize(size, h) { h = imul(h, 0xCC9E2D51); h = imul(h << 15 | h >>> -15, 0x1B873593); h = imul(h << 13 | h >>> -13, 5); h = (h + 0xE6546B64 | 0) ^ size; h = imul(h ^ h >>> 16, 0x85EBCA6B); h = imul(h ^ h >>> 13, 0xC2B2AE35); h = smi(h ^ h >>> 16); return h; } function hashMerge(a, b) { return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int } var Immutable = { Iterable: Iterable, Seq: Seq, Collection: Collection, Map: Map, OrderedMap: OrderedMap, List: List, Stack: Stack, Set: Set, OrderedSet: OrderedSet, Record: Record, Range: Range, Repeat: Repeat, is: is, fromJS: fromJS }; return Immutable; })); /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (true) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 11 */ /***/ (function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function(useSourceMap) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item, useSourceMap); if(item[2]) { return "@media " + item[2] + "{" + content + "}"; } else { return content; } }).join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; function cssWithMappingToString(item, useSourceMap) { var content = item[1] || ''; var cssMapping = item[3]; if (!cssMapping) { return content; } if (useSourceMap && typeof btoa === 'function') { var sourceMapping = toComment(cssMapping); var sourceURLs = cssMapping.sources.map(function (source) { return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */' }); return [content].concat(sourceURLs).concat([sourceMapping]).join('\n'); } return [content].join('\n'); } // Adapted from convert-source-map (MIT) function toComment(sourceMap) { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; return '/*# ' + data + ' */'; } /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}; var memoize = function (fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }; var isOldIE = memoize(function () { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 return window && document && document.all && !window.atob; }); var getElement = (function (fn) { var memo = {}; return function(selector) { if (typeof memo[selector] === "undefined") { memo[selector] = fn.call(this, selector); } return memo[selector] }; })(function (target) { return document.querySelector(target) }); var singleton = null; var singletonCounter = 0; var stylesInsertedAtTop = []; var fixUrls = __webpack_require__(504); module.exports = function(list, options) { if (typeof DEBUG !== "undefined" && DEBUG) { if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; options.attrs = typeof options.attrs === "object" ? options.attrs : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of \n ' + domainScript + '\n \n \n
\n \n ' + domainInput + '\n \n
\n \n \n '; } }, { key: 'initIframeSrc', value: function initIframeSrc() { if (this.domain) { this.getIframeNode().src = 'javascript:void((function(){\n var d = document;\n d.open();\n d.domain=\'' + this.domain + '\';\n d.write(\'\');\n d.close();\n })())'; } } }, { key: 'initIframe', value: function initIframe() { var iframeNode = this.getIframeNode(); var win = iframeNode.contentWindow; var doc = void 0; this.domain = this.domain || ''; this.initIframeSrc(); try { doc = win.document; } catch (e) { this.domain = document.domain; this.initIframeSrc(); win = iframeNode.contentWindow; doc = win.document; } doc.open('text/html', 'replace'); doc.write(this.getIframeHTML(this.domain)); doc.close(); this.getFormInputNode().onchange = this.onChange; } }, { key: 'endUpload', value: function endUpload() { if (this.state.uploading) { this.file = {}; // hack avoid batch this.state.uploading = false; this.setState({ uploading: false }); this.initIframe(); } } }, { key: 'startUpload', value: function startUpload() { if (!this.state.uploading) { this.state.uploading = true; this.setState({ uploading: true }); } } }, { key: 'updateIframeWH', value: function updateIframeWH() { var rootNode = __WEBPACK_IMPORTED_MODULE_8_react_dom___default.a.findDOMNode(this); var iframeNode = this.getIframeNode(); iframeNode.style.height = rootNode.offsetHeight + 'px'; iframeNode.style.width = rootNode.offsetWidth + 'px'; } }, { key: 'abort', value: function abort(file) { if (file) { var uid = file; if (file && file.uid) { uid = file.uid; } if (uid === this.file.uid) { this.endUpload(); } } else { this.endUpload(); } } }, { key: 'post', value: function post(file) { var _this4 = this; var formNode = this.getFormNode(); var dataSpan = this.getFormDataNode(); var data = this.props.data; var onStart = this.props.onStart; if (typeof data === 'function') { data = data(file); } var inputs = document.createDocumentFragment(); for (var key in data) { if (data.hasOwnProperty(key)) { var input = document.createElement('input'); input.setAttribute('name', key); input.value = data[key]; inputs.appendChild(input); } } dataSpan.appendChild(inputs); new Promise(function (resolve) { var action = _this4.props.action; if (typeof action === 'function') { return resolve(action(file)); } resolve(action); }).then(function (action) { formNode.setAttribute('action', action); formNode.submit(); dataSpan.innerHTML = ''; onStart(file); }); } }, { key: 'render', value: function render() { var _classNames; var _props = this.props, Tag = _props.component, disabled = _props.disabled, className = _props.className, prefixCls = _props.prefixCls, children = _props.children, style = _props.style; var iframeStyle = __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_extends___default()({}, IFRAME_STYLE, { display: this.state.uploading || disabled ? 'none' : '' }); var cls = __WEBPACK_IMPORTED_MODULE_9_classnames___default()((_classNames = {}, __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_defineProperty___default()(_classNames, prefixCls, true), __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_defineProperty___default()(_classNames, prefixCls + '-disabled', disabled), __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_defineProperty___default()(_classNames, className, className), _classNames)); return __WEBPACK_IMPORTED_MODULE_6_react___default.a.createElement( Tag, { className: cls, style: __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_extends___default()({ position: 'relative', zIndex: 0 }, style) }, __WEBPACK_IMPORTED_MODULE_6_react___default.a.createElement('iframe', { ref: this.saveIframe, onLoad: this.onLoad, style: iframeStyle }), children ); } }]); return IframeUploader; }(__WEBPACK_IMPORTED_MODULE_6_react__["Component"]); IframeUploader.propTypes = { component: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.string, style: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.object, disabled: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.bool, prefixCls: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.string, className: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.string, accept: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.string, onStart: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.func, multiple: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.bool, children: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.any, data: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.object, __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.func]), action: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.string, __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.func]), name: __WEBPACK_IMPORTED_MODULE_7_prop_types___default.a.string }; /* harmony default export */ __webpack_exports__["a"] = (IframeUploader); /***/ }), /* 894 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (true) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }), /* 895 */ /***/ (function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(896), baseUniq = __webpack_require__(925); /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, baseIteratee(iteratee, 2)) : []; } module.exports = uniqBy; /***/ }), /* 896 */ /***/ (function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(897), baseMatchesProperty = __webpack_require__(919), identity = __webpack_require__(183), isArray = __webpack_require__(48), property = __webpack_require__(922); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }), /* 897 */ /***/ (function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(898), getMatchData = __webpack_require__(918), matchesStrictComparable = __webpack_require__(435); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }), /* 898 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(179), baseIsEqual = __webpack_require__(428); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }), /* 899 */ /***/ (function(module, exports, __webpack_require__) { var Stack = __webpack_require__(179), equalArrays = __webpack_require__(429), equalByTag = __webpack_require__(903), equalObjects = __webpack_require__(905), getTag = __webpack_require__(914), isArray = __webpack_require__(48), isBuffer = __webpack_require__(181), isTypedArray = __webpack_require__(182); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }), /* 900 */ /***/ (function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }), /* 901 */ /***/ (function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }), /* 902 */ /***/ (function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }), /* 903 */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(116), Uint8Array = __webpack_require__(400), eq = __webpack_require__(94), equalArrays = __webpack_require__(429), mapToArray = __webpack_require__(904), setToArray = __webpack_require__(188); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }), /* 904 */ /***/ (function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }), /* 905 */ /***/ (function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(906); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; /***/ }), /* 906 */ /***/ (function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(907), getSymbols = __webpack_require__(909), keys = __webpack_require__(432); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }), /* 907 */ /***/ (function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(908), isArray = __webpack_require__(48); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }), /* 908 */ /***/ (function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }), /* 909 */ /***/ (function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(910), stubArray = __webpack_require__(911); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }), /* 910 */ /***/ (function(module, exports) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }), /* 911 */ /***/ (function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }), /* 912 */ /***/ (function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(180), nativeKeys = __webpack_require__(913); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }), /* 913 */ /***/ (function(module, exports, __webpack_require__) { var overArg = __webpack_require__(402); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }), /* 914 */ /***/ (function(module, exports, __webpack_require__) { var DataView = __webpack_require__(915), Map = __webpack_require__(171), Promise = __webpack_require__(916), Set = __webpack_require__(433), WeakMap = __webpack_require__(917), baseGetTag = __webpack_require__(79), toSource = __webpack_require__(389); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }), /* 915 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(68), root = __webpack_require__(43); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }), /* 916 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(68), root = __webpack_require__(43); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }), /* 917 */ /***/ (function(module, exports, __webpack_require__) { var getNative = __webpack_require__(68), root = __webpack_require__(43); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }), /* 918 */ /***/ (function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(434), keys = __webpack_require__(432); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }), /* 919 */ /***/ (function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(428), get = __webpack_require__(175), hasIn = __webpack_require__(920), isKey = __webpack_require__(167), isStrictComparable = __webpack_require__(434), matchesStrictComparable = __webpack_require__(435), toKey = __webpack_require__(95); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }), /* 920 */ /***/ (function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(921), hasPath = __webpack_require__(387); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }), /* 921 */ /***/ (function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }), /* 922 */ /***/ (function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(923), basePropertyDeep = __webpack_require__(924), isKey = __webpack_require__(167), toKey = __webpack_require__(95); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }), /* 923 */ /***/ (function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }), /* 924 */ /***/ (function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(392); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }), /* 925 */ /***/ (function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(430), arrayIncludes = __webpack_require__(926), arrayIncludesWith = __webpack_require__(931), cacheHas = __webpack_require__(431), createSet = __webpack_require__(932), setToArray = __webpack_require__(188); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseUniq; /***/ }), /* 926 */ /***/ (function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(927); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }), /* 927 */ /***/ (function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(928), baseIsNaN = __webpack_require__(929), strictIndexOf = __webpack_require__(930); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }), /* 928 */ /***/ (function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }), /* 929 */ /***/ (function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }), /* 930 */ /***/ (function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }), /* 931 */ /***/ (function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }), /* 932 */ /***/ (function(module, exports, __webpack_require__) { var Set = __webpack_require__(433), noop = __webpack_require__(933), setToArray = __webpack_require__(188); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; module.exports = createSet; /***/ }), /* 933 */ /***/ (function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }), /* 934 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var React = _interopRequireWildcard(__webpack_require__(0)); var _rcAnimate = _interopRequireDefault(__webpack_require__(45)); var _icon = _interopRequireDefault(__webpack_require__(13)); var _tooltip = _interopRequireDefault(__webpack_require__(54)); var _progress = _interopRequireDefault(__webpack_require__(935)); var _classnames = _interopRequireDefault(__webpack_require__(3)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var imageTypes = ['image', 'webp', 'png', 'svg', 'gif', 'jpg', 'jpeg', 'bmp']; // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL var previewFile = function previewFile(file, callback) { if (file.type && !imageTypes.includes(file.type)) { callback(''); } var reader = new FileReader(); reader.onloadend = function () { return callback(reader.result); }; reader.readAsDataURL(file); }; var extname = function extname(url) { if (!url) { return ''; } var temp = url.split('/'); var filename = temp[temp.length - 1]; var filenameWithoutSuffix = filename.split(/#|\?/)[0]; return (/\.[^./\\]*$/.exec(filenameWithoutSuffix) || [''])[0]; }; var isImageUrl = function isImageUrl(file) { if (imageTypes.includes(file.type)) { return true; } var url = file.thumbUrl || file.url; var extension = extname(url); if (/^data:image\//.test(url) || /(webp|svg|png|gif|jpg|jpeg|bmp)$/i.test(extension)) { return true; } else if (/^data:/.test(url)) { // other file types of base64 return false; } else if (extension) { // other file types which have extension return false; } return true; }; var UploadList = /*#__PURE__*/ function (_React$Component) { _inherits(UploadList, _React$Component); function UploadList() { var _this; _classCallCheck(this, UploadList); _this = _possibleConstructorReturn(this, _getPrototypeOf(UploadList).apply(this, arguments)); _this.handleClose = function (file) { var onRemove = _this.props.onRemove; if (onRemove) { onRemove(file); } }; _this.handlePreview = function (file, e) { var onPreview = _this.props.onPreview; if (!onPreview) { return; } e.preventDefault(); return onPreview(file); }; return _this; } _createClass(UploadList, [{ key: "componentDidUpdate", value: function componentDidUpdate() { var _this2 = this; if (this.props.listType !== 'picture' && this.props.listType !== 'picture-card') { return; } (this.props.items || []).forEach(function (file) { if (typeof document === 'undefined' || typeof window === 'undefined' || !window.FileReader || !window.File || !(file.originFileObj instanceof File) || file.thumbUrl !== undefined) { return; } /*eslint-disable */ file.thumbUrl = ''; /*eslint-enable */ previewFile(file.originFileObj, function (previewDataUrl) { /*eslint-disable */ file.thumbUrl = previewDataUrl; /*eslint-enable */ _this2.forceUpdate(); }); }); } }, { key: "render", value: function render() { var _this3 = this, _classNames2; var _this$props = this.props, prefixCls = _this$props.prefixCls, _this$props$items = _this$props.items, items = _this$props$items === void 0 ? [] : _this$props$items, listType = _this$props.listType, showPreviewIcon = _this$props.showPreviewIcon, showRemoveIcon = _this$props.showRemoveIcon, locale = _this$props.locale; var list = items.map(function (file) { var _classNames; var progress; var icon = React.createElement(_icon["default"], { type: file.status === 'uploading' ? 'loading' : 'paper-clip' }); if (listType === 'picture' || listType === 'picture-card') { if (listType === 'picture-card' && file.status === 'uploading') { icon = React.createElement("div", { className: "".concat(prefixCls, "-list-item-uploading-text") }, locale.uploading); } else if (!file.thumbUrl && !file.url) { icon = React.createElement(_icon["default"], { className: "".concat(prefixCls, "-list-item-thumbnail"), type: "picture", theme: "twoTone" }); } else { var thumbnail = isImageUrl(file) ? React.createElement("img", { src: file.thumbUrl || file.url, alt: file.name }) : React.createElement(_icon["default"], { type: "file", className: "".concat(prefixCls, "-list-item-icon"), theme: "twoTone" }); icon = React.createElement("a", { className: "".concat(prefixCls, "-list-item-thumbnail"), onClick: function onClick(e) { return _this3.handlePreview(file, e); }, href: file.url || file.thumbUrl, target: "_blank", rel: "noopener noreferrer" }, thumbnail); } } if (file.status === 'uploading') { // show loading icon if upload progress listener is disabled var loadingProgress = 'percent' in file ? React.createElement(_progress["default"], _extends({ type: "line" }, _this3.props.progressAttr, { percent: file.percent })) : null; progress = React.createElement("div", { className: "".concat(prefixCls, "-list-item-progress"), key: "progress" }, loadingProgress); } var infoUploadingClass = (0, _classnames["default"])((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-list-item"), true), _defineProperty(_classNames, "".concat(prefixCls, "-list-item-").concat(file.status), true), _classNames)); var linkProps = typeof file.linkProps === 'string' ? JSON.parse(file.linkProps) : file.linkProps; var preview = file.url ? React.createElement("a", _extends({ target: "_blank", rel: "noopener noreferrer", className: "".concat(prefixCls, "-list-item-name"), title: file.name }, linkProps, { href: file.url, onClick: function onClick(e) { return _this3.handlePreview(file, e); } }), file.name) : React.createElement("span", { className: "".concat(prefixCls, "-list-item-name"), onClick: function onClick(e) { return _this3.handlePreview(file, e); }, title: file.name }, file.name); var style = { pointerEvents: 'none', opacity: 0.5 }; var previewIcon = showPreviewIcon ? React.createElement("a", { href: file.url || file.thumbUrl, target: "_blank", rel: "noopener noreferrer", style: file.url || file.thumbUrl ? undefined : style, onClick: function onClick(e) { return _this3.handlePreview(file, e); }, title: locale.previewFile }, React.createElement(_icon["default"], { type: "eye-o" })) : null; var removeIcon = showRemoveIcon ? React.createElement(_icon["default"], { type: "delete", title: locale.removeFile, onClick: function onClick() { return _this3.handleClose(file); } }) : null; var removeIconClose = showRemoveIcon ? React.createElement(_icon["default"], { type: "close", title: locale.removeFile, onClick: function onClick() { return _this3.handleClose(file); } }) : null; var actions = listType === 'picture-card' && file.status !== 'uploading' ? React.createElement("span", { className: "".concat(prefixCls, "-list-item-actions") }, previewIcon, removeIcon) : removeIconClose; var message; if (file.response && typeof file.response === 'string') { message = file.response; } else { message = file.error && file.error.statusText || locale.uploadError; } var iconAndPreview = file.status === 'error' ? React.createElement(_tooltip["default"], { title: message }, icon, preview) : React.createElement("span", null, icon, preview); return React.createElement("div", { className: infoUploadingClass, key: file.uid }, React.createElement("div", { className: "".concat(prefixCls, "-list-item-info") }, iconAndPreview), actions, React.createElement(_rcAnimate["default"], { transitionName: "fade", component: "" }, progress)); }); var listClassNames = (0, _classnames["default"])((_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefixCls, "-list"), true), _defineProperty(_classNames2, "".concat(prefixCls, "-list-").concat(listType), true), _classNames2)); var animationDirection = listType === 'picture-card' ? 'animate-inline' : 'animate'; return React.createElement(_rcAnimate["default"], { transitionName: "".concat(prefixCls, "-").concat(animationDirection), component: "div", className: listClassNames }, list); } }]); return UploadList; }(React.Component); exports["default"] = UploadList; UploadList.defaultProps = { listType: 'text', progressAttr: { strokeWidth: 2, showInfo: false }, prefixCls: 'ant-upload', showRemoveIcon: true, showPreviewIcon: true }; /***/ }), /* 935 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _progress = _interopRequireDefault(__webpack_require__(936)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _default = _progress["default"]; exports["default"] = _default; /***/ }), /* 936 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var PropTypes = _interopRequireWildcard(__webpack_require__(2)); var React = _interopRequireWildcard(__webpack_require__(0)); var _icon = _interopRequireDefault(__webpack_require__(13)); var _rcProgress = __webpack_require__(937); var _classnames = _interopRequireDefault(__webpack_require__(3)); var _type = __webpack_require__(38); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var __rest = void 0 && (void 0).__rest || function (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; }; var statusColorMap = { normal: '#108ee9', exception: '#ff5500', success: '#87d068' }; var ProgressTypes = (0, _type.tuple)('line', 'circle', 'dashboard'); var ProgressStatuses = (0, _type.tuple)('normal', 'exception', 'active', 'success'); var validProgress = function validProgress(progress) { if (!progress || progress < 0) { return 0; } else if (progress > 100) { return 100; } return progress; }; var Progress = /*#__PURE__*/ function (_React$Component) { _inherits(Progress, _React$Component); function Progress() { _classCallCheck(this, Progress); return _possibleConstructorReturn(this, _getPrototypeOf(Progress).apply(this, arguments)); } _createClass(Progress, [{ key: "render", value: function render() { var _classNames; var props = this.props; var prefixCls = props.prefixCls, className = props.className, _props$percent = props.percent, percent = _props$percent === void 0 ? 0 : _props$percent, status = props.status, format = props.format, trailColor = props.trailColor, size = props.size, successPercent = props.successPercent, type = props.type, strokeWidth = props.strokeWidth, width = props.width, showInfo = props.showInfo, _props$gapDegree = props.gapDegree, gapDegree = _props$gapDegree === void 0 ? 0 : _props$gapDegree, gapPosition = props.gapPosition, strokeColor = props.strokeColor, _props$strokeLinecap = props.strokeLinecap, strokeLinecap = _props$strokeLinecap === void 0 ? 'round' : _props$strokeLinecap, restProps = __rest(props, ["prefixCls", "className", "percent", "status", "format", "trailColor", "size", "successPercent", "type", "strokeWidth", "width", "showInfo", "gapDegree", "gapPosition", "strokeColor", "strokeLinecap"]); var progressStatus = parseInt(successPercent ? successPercent.toString() : percent.toString(), 10) >= 100 && !('status' in props) ? 'success' : status || 'normal'; var progressInfo; var progress; var textFormatter = format || function (percentNumber) { return "".concat(percentNumber, "%"); }; if (showInfo) { var text; var iconType = type === 'circle' || type === 'dashboard' ? '' : '-circle'; if (format || progressStatus !== 'exception' && progressStatus !== 'success') { text = textFormatter(validProgress(percent), validProgress(successPercent)); } else if (progressStatus === 'exception') { text = React.createElement(_icon["default"], { type: "close".concat(iconType), theme: type === 'line' ? 'filled' : 'outlined' }); } else if (progressStatus === 'success') { text = React.createElement(_icon["default"], { type: "check".concat(iconType), theme: type === 'line' ? 'filled' : 'outlined' }); } progressInfo = React.createElement("span", { className: "".concat(prefixCls, "-text"), title: typeof text === 'string' ? text : undefined }, text); } if (type === 'line') { var percentStyle = { width: "".concat(validProgress(percent), "%"), height: strokeWidth || (size === 'small' ? 6 : 8), background: strokeColor, borderRadius: strokeLinecap === 'square' ? 0 : '100px' }; var successPercentStyle = { width: "".concat(validProgress(successPercent), "%"), height: strokeWidth || (size === 'small' ? 6 : 8), borderRadius: strokeLinecap === 'square' ? 0 : '100px' }; var successSegment = successPercent !== undefined ? React.createElement("div", { className: "".concat(prefixCls, "-success-bg"), style: successPercentStyle }) : null; progress = React.createElement("div", null, React.createElement("div", { className: "".concat(prefixCls, "-outer") }, React.createElement("div", { className: "".concat(prefixCls, "-inner") }, React.createElement("div", { className: "".concat(prefixCls, "-bg"), style: percentStyle }), successSegment)), progressInfo); } else if (type === 'circle' || type === 'dashboard') { var circleSize = width || 120; var circleStyle = { width: circleSize, height: circleSize, fontSize: circleSize * 0.15 + 6 }; var circleWidth = strokeWidth || 6; var gapPos = gapPosition || type === 'dashboard' && 'bottom' || 'top'; var gapDeg = gapDegree || type === 'dashboard' && 75; progress = React.createElement("div", { className: "".concat(prefixCls, "-inner"), style: circleStyle }, React.createElement(_rcProgress.Circle, { percent: validProgress(percent), strokeWidth: circleWidth, trailWidth: circleWidth, strokeColor: strokeColor || statusColorMap[progressStatus], strokeLinecap: strokeLinecap, trailColor: trailColor, prefixCls: prefixCls, gapDegree: gapDeg, gapPosition: gapPos }), progressInfo); } var classString = (0, _classnames["default"])(prefixCls, (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-").concat(type === 'dashboard' && 'circle' || type), true), _defineProperty(_classNames, "".concat(prefixCls, "-status-").concat(progressStatus), true), _defineProperty(_classNames, "".concat(prefixCls, "-show-info"), showInfo), _defineProperty(_classNames, "".concat(prefixCls, "-").concat(size), size), _classNames), className); return React.createElement("div", _extends({}, restProps, { className: classString }), progress); } }]); return Progress; }(React.Component); exports["default"] = Progress; Progress.defaultProps = { type: 'line', percent: 0, showInfo: true, trailColor: '#f3f3f3', prefixCls: 'ant-progress', size: 'default' }; Progress.propTypes = { status: PropTypes.oneOf(ProgressStatuses), type: PropTypes.oneOf(ProgressTypes), showInfo: PropTypes.bool, percent: PropTypes.number, width: PropTypes.number, strokeWidth: PropTypes.number, strokeLinecap: PropTypes.oneOf(['round', 'square']), strokeColor: PropTypes.string, trailColor: PropTypes.string, format: PropTypes.func, gapDegree: PropTypes.number, "default": PropTypes.oneOf(['default', 'small']) }; /***/ }), /* 937 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Line__ = __webpack_require__(938); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Circle__ = __webpack_require__(939); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return __WEBPACK_IMPORTED_MODULE_0__Line__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Circle", function() { return __WEBPACK_IMPORTED_MODULE_1__Circle__["a"]; }); /* harmony default export */ __webpack_exports__["default"] = ({ Line: __WEBPACK_IMPORTED_MODULE_0__Line__["a" /* default */], Circle: __WEBPACK_IMPORTED_MODULE_1__Circle__["a" /* default */] }); /***/ }), /* 938 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties__ = __webpack_require__(20); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_react__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5_react__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__enhancer__ = __webpack_require__(436); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__types__ = __webpack_require__(437); var Line = function (_Component) { __WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits___default()(Line, _Component); function Line() { __WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck___default()(this, Line); return __WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn___default()(this, _Component.apply(this, arguments)); } Line.prototype.render = function render() { var _this2 = this; var _props = this.props, className = _props.className, percent = _props.percent, prefixCls = _props.prefixCls, strokeColor = _props.strokeColor, strokeLinecap = _props.strokeLinecap, strokeWidth = _props.strokeWidth, style = _props.style, trailColor = _props.trailColor, trailWidth = _props.trailWidth, restProps = __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties___default()(_props, ['className', 'percent', 'prefixCls', 'strokeColor', 'strokeLinecap', 'strokeWidth', 'style', 'trailColor', 'trailWidth']); delete restProps.gapPosition; var pathStyle = { strokeDasharray: '100px, 100px', strokeDashoffset: 100 - percent + 'px', transition: 'stroke-dashoffset 0.3s ease 0s, stroke 0.3s linear' }; var center = strokeWidth / 2; var right = 100 - strokeWidth / 2; var pathString = 'M ' + (strokeLinecap === 'round' ? center : 0) + ',' + center + '\n L ' + (strokeLinecap === 'round' ? right : 100) + ',' + center; var viewBoxString = '0 0 100 ' + strokeWidth; return __WEBPACK_IMPORTED_MODULE_5_react___default.a.createElement( 'svg', __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({ className: prefixCls + '-line ' + className, viewBox: viewBoxString, preserveAspectRatio: 'none', style: style }, restProps), __WEBPACK_IMPORTED_MODULE_5_react___default.a.createElement('path', { className: prefixCls + '-line-trail', d: pathString, strokeLinecap: strokeLinecap, stroke: trailColor, strokeWidth: trailWidth || strokeWidth, fillOpacity: '0' }), __WEBPACK_IMPORTED_MODULE_5_react___default.a.createElement('path', { className: prefixCls + '-line-path', d: pathString, strokeLinecap: strokeLinecap, stroke: strokeColor, strokeWidth: strokeWidth, fillOpacity: '0', ref: function ref(path) { _this2.path = path; }, style: pathStyle }) ); }; return Line; }(__WEBPACK_IMPORTED_MODULE_5_react__["Component"]); Line.propTypes = __WEBPACK_IMPORTED_MODULE_7__types__["b" /* propTypes */]; Line.defaultProps = __WEBPACK_IMPORTED_MODULE_7__types__["a" /* defaultProps */]; /* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_6__enhancer__["a" /* default */])(Line)); /***/ }), /* 939 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties__ = __webpack_require__(20); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_react__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5_react__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_prop_types__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_prop_types___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6_prop_types__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__enhancer__ = __webpack_require__(436); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__types__ = __webpack_require__(437); /* eslint react/prop-types: 0 */ var Circle = function (_Component) { __WEBPACK_IMPORTED_MODULE_4_babel_runtime_helpers_inherits___default()(Circle, _Component); function Circle() { __WEBPACK_IMPORTED_MODULE_2_babel_runtime_helpers_classCallCheck___default()(this, Circle); return __WEBPACK_IMPORTED_MODULE_3_babel_runtime_helpers_possibleConstructorReturn___default()(this, _Component.apply(this, arguments)); } Circle.prototype.getPathStyles = function getPathStyles() { var _props = this.props, percent = _props.percent, strokeWidth = _props.strokeWidth, strokeColor = _props.strokeColor, _props$gapDegree = _props.gapDegree, gapDegree = _props$gapDegree === undefined ? 0 : _props$gapDegree, gapPosition = _props.gapPosition; var radius = 50 - strokeWidth / 2; var beginPositionX = 0; var beginPositionY = -radius; var endPositionX = 0; var endPositionY = -2 * radius; switch (gapPosition) { case 'left': beginPositionX = -radius; beginPositionY = 0; endPositionX = 2 * radius; endPositionY = 0; break; case 'right': beginPositionX = radius; beginPositionY = 0; endPositionX = -2 * radius; endPositionY = 0; break; case 'bottom': beginPositionY = radius; endPositionY = 2 * radius; break; default: } var pathString = 'M 50,50 m ' + beginPositionX + ',' + beginPositionY + '\n a ' + radius + ',' + radius + ' 0 1 1 ' + endPositionX + ',' + -endPositionY + '\n a ' + radius + ',' + radius + ' 0 1 1 ' + -endPositionX + ',' + endPositionY; var len = Math.PI * 2 * radius; var trailPathStyle = { strokeDasharray: len - gapDegree + 'px ' + len + 'px', strokeDashoffset: '-' + gapDegree / 2 + 'px', transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s' }; var strokePathStyle = { stroke: strokeColor, strokeDasharray: percent / 100 * (len - gapDegree) + 'px ' + len + 'px', strokeDashoffset: '-' + gapDegree / 2 + 'px', transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s' // eslint-disable-line }; return { pathString: pathString, trailPathStyle: trailPathStyle, strokePathStyle: strokePathStyle }; }; Circle.prototype.render = function render() { var _this2 = this; var _props2 = this.props, prefixCls = _props2.prefixCls, strokeWidth = _props2.strokeWidth, trailWidth = _props2.trailWidth, percent = _props2.percent, trailColor = _props2.trailColor, strokeLinecap = _props2.strokeLinecap, style = _props2.style, className = _props2.className, restProps = __WEBPACK_IMPORTED_MODULE_1_babel_runtime_helpers_objectWithoutProperties___default()(_props2, ['prefixCls', 'strokeWidth', 'trailWidth', 'percent', 'trailColor', 'strokeLinecap', 'style', 'className']); var _getPathStyles = this.getPathStyles(), pathString = _getPathStyles.pathString, trailPathStyle = _getPathStyles.trailPathStyle, strokePathStyle = _getPathStyles.strokePathStyle; delete restProps.percent; delete restProps.gapDegree; delete restProps.gapPosition; delete restProps.strokeColor; return __WEBPACK_IMPORTED_MODULE_5_react___default.a.createElement( 'svg', __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({ className: prefixCls + '-circle ' + className, viewBox: '0 0 100 100', style: style }, restProps), __WEBPACK_IMPORTED_MODULE_5_react___default.a.createElement('path', { className: prefixCls + '-circle-trail', d: pathString, stroke: trailColor, strokeWidth: trailWidth || strokeWidth, fillOpacity: '0', style: trailPathStyle }), __WEBPACK_IMPORTED_MODULE_5_react___default.a.createElement('path', { className: prefixCls + '-circle-path', d: pathString, strokeLinecap: strokeLinecap, strokeWidth: this.props.percent === 0 ? 0 : strokeWidth, fillOpacity: '0', ref: function ref(path) { _this2.path = path; }, style: strokePathStyle }) ); }; return Circle; }(__WEBPACK_IMPORTED_MODULE_5_react__["Component"]); Circle.propTypes = __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, __WEBPACK_IMPORTED_MODULE_8__types__["b" /* propTypes */], { gapPosition: __WEBPACK_IMPORTED_MODULE_6_prop_types___default.a.oneOf(['top', 'bottom', 'left', 'right']) }); Circle.defaultProps = __WEBPACK_IMPORTED_MODULE_0_babel_runtime_helpers_extends___default()({}, __WEBPACK_IMPORTED_MODULE_8__types__["a" /* defaultProps */], { gapPosition: 'top' }); /* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_7__enhancer__["a" /* default */])(Circle)); /***/ }), /* 940 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.T = T; exports.fileToObject = fileToObject; exports.genPercentAdd = genPercentAdd; exports.getFileItem = getFileItem; exports.removeFileItem = removeFileItem; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function T() { return true; } // Fix IE file.status problem // via coping a new Object function fileToObject(file) { return _extends({}, file, { lastModified: file.lastModified, lastModifiedDate: file.lastModifiedDate, name: file.name, size: file.size, type: file.type, uid: file.uid, percent: 0, originFileObj: file }); } /** * 生成Progress percent: 0.1 -> 0.98 * - for ie */ function genPercentAdd() { var k = 0.1; var i = 0.01; var end = 0.98; return function (s) { var start = s; if (start >= end) { return start; } start += k; k = k - i; if (k < 0.001) { k = 0.001; } return start; }; } function getFileItem(file, fileList) { var matchKey = file.uid !== undefined ? 'uid' : 'name'; return fileList.filter(function (item) { return item[matchKey] === file[matchKey]; })[0]; } function removeFileItem(file, fileList) { var matchKey = file.uid !== undefined ? 'uid' : 'name'; var removed = fileList.filter(function (item) { return item[matchKey] !== file[matchKey]; }); if (removed.length === fileList.length) { return null; } return removed; } /***/ }), /* 941 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var React = _interopRequireWildcard(__webpack_require__(0)); var _Upload = _interopRequireDefault(__webpack_require__(426)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Dragger = /*#__PURE__*/ function (_React$Component) { _inherits(Dragger, _React$Component); function Dragger() { _classCallCheck(this, Dragger); return _possibleConstructorReturn(this, _getPrototypeOf(Dragger).apply(this, arguments)); } _createClass(Dragger, [{ key: "render", value: function render() { var props = this.props; return React.createElement(_Upload["default"], _extends({}, props, { type: "drag", style: _extends({}, props.style, { height: props.height }) })); } }]); return Dragger; }(React.Component); exports["default"] = Dragger; /***/ }), /* 942 */ /***/ (function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__webpack_require__(0), __webpack_require__(943), __webpack_require__(83), __webpack_require__(9), __webpack_require__(465), __webpack_require__(8), __webpack_require__(1051), __webpack_require__(464)); else if(typeof define === 'function' && define.amd) define(["react", "braft-utils", "draft-js", "immutable", "braft-convert", "react-dom", "braft-finder", "draftjs-utils"], factory); else { var a = typeof exports === 'object' ? factory(require("react"), require("braft-utils"), require("draft-js"), require("immutable"), require("braft-convert"), require("react-dom"), require("braft-finder"), require("draftjs-utils")) : factory(root["react"], root["braft-utils"], root["draft-js"], root["immutable"], root["braft-convert"], root["react-dom"], root["braft-finder"], root["draftjs-utils"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(window, function(__WEBPACK_EXTERNAL_MODULE__0__, __WEBPACK_EXTERNAL_MODULE__3__, __WEBPACK_EXTERNAL_MODULE__10__, __WEBPACK_EXTERNAL_MODULE__13__, __WEBPACK_EXTERNAL_MODULE__14__, __WEBPACK_EXTERNAL_MODULE__15__, __WEBPACK_EXTERNAL_MODULE__17__, __WEBPACK_EXTERNAL_MODULE__23__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 39); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__0__; /***/ }), /* 1 */ /***/ (function(module, exports) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } module.exports = _assertThisInitialized; /***/ }), /* 2 */ /***/ (function(module, exports) { function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__3__; /***/ }), /* 4 */ /***/ (function(module, exports) { function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = _classCallCheck; /***/ }), /* 5 */ /***/ (function(module, exports) { function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } module.exports = _createClass; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { var _typeof = __webpack_require__(16); var assertThisInitialized = __webpack_require__(1); function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } module.exports = _possibleConstructorReturn; /***/ }), /* 7 */ /***/ (function(module, exports) { function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } module.exports = _getPrototypeOf; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var setPrototypeOf = __webpack_require__(26); function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } module.exports = _inherits; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(2); function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { defineProperty(target, key, source[key]); }); } return target; } module.exports = _objectSpread; /***/ }), /* 10 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__10__; /***/ }), /* 11 */ /***/ (function(module, exports) { function _extends() { module.exports = _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } module.exports = _extends; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { var arrayWithoutHoles = __webpack_require__(27); var iterableToArray = __webpack_require__(28); var nonIterableSpread = __webpack_require__(29); function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } module.exports = _toConsumableArray; /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__13__; /***/ }), /* 14 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__14__; /***/ }), /* 15 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__15__; /***/ }), /* 16 */ /***/ (function(module, exports) { function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { module.exports = _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); }; } return _typeof(obj); } module.exports = _typeof; /***/ }), /* 17 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__17__; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { var Immutable = __webpack_require__(13); var KEY_SEPARATOR = '-'; function MultiDecorator(decorators) { this.decorators = Immutable.List(decorators); } /** Return list of decoration IDs per character @param {ContentBlock} @return {List} */ MultiDecorator.prototype.getDecorations = function(block) { var decorations = Array(block.getText().length).fill(null); this.decorators.forEach(function(decorator, i) { var _decorations = decorator.getDecorations(block); _decorations.forEach(function(key, offset) { if (!key) { return; } key = i + KEY_SEPARATOR + key; decorations[offset] = key; }); }); return Immutable.List(decorations); }; /** Return component to render a decoration @param {String} @return {Function} */ MultiDecorator.prototype.getComponentForKey = function(key) { var decorator = this.getDecoratorForKey(key); return decorator.getComponentForKey( this.getInnerKey(key) ); }; /** Return props to render a decoration @param {String} @return {Object} */ MultiDecorator.prototype.getPropsForKey = function(key) { var decorator = this.getDecoratorForKey(key); return decorator.getPropsForKey( this.getInnerKey(key) ); }; /** Return a decorator for a specific key @param {String} @return {Decorator} */ MultiDecorator.prototype.getDecoratorForKey = function(key) { var parts = key.split(KEY_SEPARATOR); var index = Number(parts[0]); return this.decorators.get(index); }; /** Return inner key for a decorator @param {String} @return {String} */ MultiDecorator.prototype.getInnerKey = function(key) { var parts = key.split(KEY_SEPARATOR); return parts.slice(1).join(KEY_SEPARATOR); }; module.exports = MultiDecorator; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CharacterMetadata * @format * */ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _require = __webpack_require__(13), Map = _require.Map, OrderedSet = _require.OrderedSet, Record = _require.Record; // Immutable.map is typed such that the value for every key in the map // must be the same type var EMPTY_SET = OrderedSet(); var defaultRecord = { style: EMPTY_SET, entity: null }; var CharacterMetadataRecord = Record(defaultRecord); var CharacterMetadata = function (_CharacterMetadataRec) { _inherits(CharacterMetadata, _CharacterMetadataRec); function CharacterMetadata() { _classCallCheck(this, CharacterMetadata); return _possibleConstructorReturn(this, _CharacterMetadataRec.apply(this, arguments)); } CharacterMetadata.prototype.getStyle = function getStyle() { return this.get('style'); }; CharacterMetadata.prototype.getEntity = function getEntity() { return this.get('entity'); }; CharacterMetadata.prototype.hasStyle = function hasStyle(style) { return this.getStyle().includes(style); }; CharacterMetadata.applyStyle = function applyStyle(record, style) { var withStyle = record.set('style', record.getStyle().add(style)); return CharacterMetadata.create(withStyle); }; CharacterMetadata.removeStyle = function removeStyle(record, style) { var withoutStyle = record.set('style', record.getStyle().remove(style)); return CharacterMetadata.create(withoutStyle); }; CharacterMetadata.applyEntity = function applyEntity(record, entityKey) { var withEntity = record.getEntity() === entityKey ? record : record.set('entity', entityKey); return CharacterMetadata.create(withEntity); }; /** * Use this function instead of the `CharacterMetadata` constructor. * Since most content generally uses only a very small number of * style/entity permutations, we can reuse these objects as often as * possible. */ CharacterMetadata.create = function create(config) { if (!config) { return EMPTY; } var defaultConfig = { style: EMPTY_SET, entity: null }; // Fill in unspecified properties, if necessary. var configMap = Map(defaultConfig).merge(config); var existing = pool.get(configMap); if (existing) { return existing; } var newCharacter = new CharacterMetadata(configMap); pool = pool.set(configMap, newCharacter); return newCharacter; }; return CharacterMetadata; }(CharacterMetadataRecord); var EMPTY = new CharacterMetadata(); var pool = Map([[Map(defaultRecord), EMPTY]]); CharacterMetadata.EMPTY = EMPTY; module.exports = CharacterMetadata; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findRangesImmutable * @format * */ /** * Search through an array to find contiguous stretches of elements that * match a specified filter function. * * When ranges are found, execute a specified `found` function to supply * the values to the caller. */ function findRangesImmutable(haystack, areEqualFn, filterFn, foundFn) { if (!haystack.size) { return; } var cursor = 0; haystack.reduce(function (value, nextValue, nextIndex) { if (!areEqualFn(value, nextValue)) { if (filterFn(value)) { foundFn(cursor, nextIndex); } cursor = nextIndex; } return nextValue; }); filterFn(haystack.last()) && foundFn(cursor, haystack.count()); } module.exports = findRangesImmutable; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { var objectWithoutPropertiesLoose = __webpack_require__(25); function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } module.exports = _objectWithoutProperties; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getFragmentFromSelection * @format * */ var getContentStateFragment = __webpack_require__(30); function getFragmentFromSelection(editorState) { var selectionState = editorState.getSelection(); if (selectionState.isCollapsed()) { return null; } return getContentStateFragment(editorState.getCurrentContent(), selectionState); } module.exports = getFragmentFromSelection; /***/ }), /* 23 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__23__; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { var arrayWithHoles = __webpack_require__(36); var iterableToArrayLimit = __webpack_require__(37); var nonIterableRest = __webpack_require__(38); function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); } module.exports = _slicedToArray; /***/ }), /* 25 */ /***/ (function(module, exports) { function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } module.exports = _objectWithoutPropertiesLoose; /***/ }), /* 26 */ /***/ (function(module, exports) { function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf; /***/ }), /* 27 */ /***/ (function(module, exports) { function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } module.exports = _arrayWithoutHoles; /***/ }), /* 28 */ /***/ (function(module, exports) { function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } module.exports = _iterableToArray; /***/ }), /* 29 */ /***/ (function(module, exports) { function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } module.exports = _nonIterableSpread; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getContentStateFragment * @format * */ var randomizeBlockMapKeys = __webpack_require__(31); var removeEntitiesAtEdges = __webpack_require__(34); var getContentStateFragment = function getContentStateFragment(contentState, selectionState) { var startKey = selectionState.getStartKey(); var startOffset = selectionState.getStartOffset(); var endKey = selectionState.getEndKey(); var endOffset = selectionState.getEndOffset(); // Edge entities should be stripped to ensure that we don't preserve // invalid partial entities when the fragment is reused. We do, however, // preserve entities that are entirely within the selection range. var contentWithoutEdgeEntities = removeEntitiesAtEdges(contentState, selectionState); var blockMap = contentWithoutEdgeEntities.getBlockMap(); var blockKeys = blockMap.keySeq(); var startIndex = blockKeys.indexOf(startKey); var endIndex = blockKeys.indexOf(endKey) + 1; return randomizeBlockMapKeys(blockMap.slice(startIndex, endIndex).map(function (block, blockKey) { var text = block.getText(); var chars = block.getCharacterList(); if (startKey === endKey) { return block.merge({ text: text.slice(startOffset, endOffset), characterList: chars.slice(startOffset, endOffset) }); } if (blockKey === startKey) { return block.merge({ text: text.slice(startOffset), characterList: chars.slice(startOffset) }); } if (blockKey === endKey) { return block.merge({ text: text.slice(0, endOffset), characterList: chars.slice(0, endOffset) }); } return block; })); }; module.exports = getContentStateFragment; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule randomizeBlockMapKeys * @format * */ var ContentBlockNode = __webpack_require__(32); var Immutable = __webpack_require__(13); var generateRandomKey = __webpack_require__(33); var OrderedMap = Immutable.OrderedMap; var randomizeContentBlockNodeKeys = function randomizeContentBlockNodeKeys(blockMap) { var newKeysRef = {}; // we keep track of root blocks in order to update subsequent sibling links var lastRootBlock = void 0; return OrderedMap(blockMap.withMutations(function (blockMapState) { blockMapState.forEach(function (block, index) { var oldKey = block.getKey(); var nextKey = block.getNextSiblingKey(); var prevKey = block.getPrevSiblingKey(); var childrenKeys = block.getChildKeys(); var parentKey = block.getParentKey(); // new key that we will use to build linking var key = generateRandomKey(); // we will add it here to re-use it later newKeysRef[oldKey] = key; if (nextKey) { var nextBlock = blockMapState.get(nextKey); if (nextBlock) { blockMapState.setIn([nextKey, 'prevSibling'], key); } else { // this can happen when generating random keys for fragments blockMapState.setIn([oldKey, 'nextSibling'], null); } } if (prevKey) { var prevBlock = blockMapState.get(prevKey); if (prevBlock) { blockMapState.setIn([prevKey, 'nextSibling'], key); } else { // this can happen when generating random keys for fragments blockMapState.setIn([oldKey, 'prevSibling'], null); } } if (parentKey && blockMapState.get(parentKey)) { var parentBlock = blockMapState.get(parentKey); var parentChildrenList = parentBlock.getChildKeys(); blockMapState.setIn([parentKey, 'children'], parentChildrenList.set(parentChildrenList.indexOf(block.getKey()), key)); } else { // blocks will then be treated as root block nodes blockMapState.setIn([oldKey, 'parent'], null); if (lastRootBlock) { blockMapState.setIn([lastRootBlock.getKey(), 'nextSibling'], key); blockMapState.setIn([oldKey, 'prevSibling'], newKeysRef[lastRootBlock.getKey()]); } lastRootBlock = blockMapState.get(oldKey); } childrenKeys.forEach(function (childKey) { var childBlock = blockMapState.get(childKey); if (childBlock) { blockMapState.setIn([childKey, 'parent'], key); } else { blockMapState.setIn([oldKey, 'children'], block.getChildKeys().filter(function (child) { return child !== childKey; })); } }); }); }).toArray().map(function (block) { return [newKeysRef[block.getKey()], block.set('key', newKeysRef[block.getKey()])]; })); }; var randomizeContentBlockKeys = function randomizeContentBlockKeys(blockMap) { return OrderedMap(blockMap.toArray().map(function (block) { var key = generateRandomKey(); return [key, block.set('key', key)]; })); }; var randomizeBlockMapKeys = function randomizeBlockMapKeys(blockMap) { var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode; if (!isTreeBasedBlockMap) { return randomizeContentBlockKeys(blockMap); } return randomizeContentBlockNodeKeys(blockMap); }; module.exports = randomizeBlockMapKeys; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ContentBlockNode * @format * * * This file is a fork of ContentBlock adding support for nesting references by * providing links to children, parent, prevSibling, and nextSibling. * * This is unstable and not part of the public API and should not be used by * production systems. This file may be update/removed without notice. */ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var CharacterMetadata = __webpack_require__(19); var Immutable = __webpack_require__(13); var findRangesImmutable = __webpack_require__(20); var List = Immutable.List, Map = Immutable.Map, OrderedSet = Immutable.OrderedSet, Record = Immutable.Record, Repeat = Immutable.Repeat; var EMPTY_SET = OrderedSet(); var defaultRecord = { parent: null, characterList: List(), data: Map(), depth: 0, key: '', text: '', type: 'unstyled', children: List(), prevSibling: null, nextSibling: null }; var haveEqualStyle = function haveEqualStyle(charA, charB) { return charA.getStyle() === charB.getStyle(); }; var haveEqualEntity = function haveEqualEntity(charA, charB) { return charA.getEntity() === charB.getEntity(); }; var decorateCharacterList = function decorateCharacterList(config) { if (!config) { return config; } var characterList = config.characterList, text = config.text; if (text && !characterList) { config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length)); } return config; }; var ContentBlockNode = function (_Record) { _inherits(ContentBlockNode, _Record); function ContentBlockNode() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultRecord; _classCallCheck(this, ContentBlockNode); return _possibleConstructorReturn(this, _Record.call(this, decorateCharacterList(props))); } ContentBlockNode.prototype.getKey = function getKey() { return this.get('key'); }; ContentBlockNode.prototype.getType = function getType() { return this.get('type'); }; ContentBlockNode.prototype.getText = function getText() { return this.get('text'); }; ContentBlockNode.prototype.getCharacterList = function getCharacterList() { return this.get('characterList'); }; ContentBlockNode.prototype.getLength = function getLength() { return this.getText().length; }; ContentBlockNode.prototype.getDepth = function getDepth() { return this.get('depth'); }; ContentBlockNode.prototype.getData = function getData() { return this.get('data'); }; ContentBlockNode.prototype.getInlineStyleAt = function getInlineStyleAt(offset) { var character = this.getCharacterList().get(offset); return character ? character.getStyle() : EMPTY_SET; }; ContentBlockNode.prototype.getEntityAt = function getEntityAt(offset) { var character = this.getCharacterList().get(offset); return character ? character.getEntity() : null; }; ContentBlockNode.prototype.getChildKeys = function getChildKeys() { return this.get('children'); }; ContentBlockNode.prototype.getParentKey = function getParentKey() { return this.get('parent'); }; ContentBlockNode.prototype.getPrevSiblingKey = function getPrevSiblingKey() { return this.get('prevSibling'); }; ContentBlockNode.prototype.getNextSiblingKey = function getNextSiblingKey() { return this.get('nextSibling'); }; ContentBlockNode.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) { findRangesImmutable(this.getCharacterList(), haveEqualStyle, filterFn, callback); }; ContentBlockNode.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) { findRangesImmutable(this.getCharacterList(), haveEqualEntity, filterFn, callback); }; return ContentBlockNode; }(Record(defaultRecord)); module.exports = ContentBlockNode; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule generateRandomKey * @format * */ var seenKeys = {}; var MULTIPLIER = Math.pow(2, 24); function generateRandomKey() { var key = void 0; while (key === undefined || seenKeys.hasOwnProperty(key) || !isNaN(+key)) { key = Math.floor(Math.random() * MULTIPLIER).toString(32); } seenKeys[key] = true; return key; } module.exports = generateRandomKey; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule removeEntitiesAtEdges * @format * */ var CharacterMetadata = __webpack_require__(19); var findRangesImmutable = __webpack_require__(20); var invariant = __webpack_require__(35); function removeEntitiesAtEdges(contentState, selectionState) { var blockMap = contentState.getBlockMap(); var entityMap = contentState.getEntityMap(); var updatedBlocks = {}; var startKey = selectionState.getStartKey(); var startOffset = selectionState.getStartOffset(); var startBlock = blockMap.get(startKey); var updatedStart = removeForBlock(entityMap, startBlock, startOffset); if (updatedStart !== startBlock) { updatedBlocks[startKey] = updatedStart; } var endKey = selectionState.getEndKey(); var endOffset = selectionState.getEndOffset(); var endBlock = blockMap.get(endKey); if (startKey === endKey) { endBlock = updatedStart; } var updatedEnd = removeForBlock(entityMap, endBlock, endOffset); if (updatedEnd !== endBlock) { updatedBlocks[endKey] = updatedEnd; } if (!Object.keys(updatedBlocks).length) { return contentState.set('selectionAfter', selectionState); } return contentState.merge({ blockMap: blockMap.merge(updatedBlocks), selectionAfter: selectionState }); } function getRemovalRange(characters, key, offset) { var removalRange; findRangesImmutable(characters, function (a, b) { return a.getEntity() === b.getEntity(); }, function (element) { return element.getEntity() === key; }, function (start, end) { if (start <= offset && end >= offset) { removalRange = { start: start, end: end }; } }); !(typeof removalRange === 'object') ? false ? undefined : invariant(false) : void 0; return removalRange; } function removeForBlock(entityMap, block, offset) { var chars = block.getCharacterList(); var charBefore = offset > 0 ? chars.get(offset - 1) : undefined; var charAfter = offset < chars.count() ? chars.get(offset) : undefined; var entityBeforeCursor = charBefore ? charBefore.getEntity() : undefined; var entityAfterCursor = charAfter ? charAfter.getEntity() : undefined; if (entityAfterCursor && entityAfterCursor === entityBeforeCursor) { var entity = entityMap.__get(entityAfterCursor); if (entity.getMutability() !== 'MUTABLE') { var _getRemovalRange = getRemovalRange(chars, entityAfterCursor, offset), start = _getRemovalRange.start, end = _getRemovalRange.end; var current; while (start < end) { current = chars.get(start); chars = chars.set(start, CharacterMetadata.applyEntity(current, null)); start++; } return block.set('characterList', chars); } } return block; } module.exports = removeEntitiesAtEdges; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (false) {} function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 36 */ /***/ (function(module, exports) { function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = _arrayWithHoles; /***/ }), /* 37 */ /***/ (function(module, exports) { function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } module.exports = _iterableToArrayLimit; /***/ }), /* 38 */ /***/ (function(module, exports) { function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } module.exports = _nonIterableRest; /***/ }), /* 39 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/typeof.js var helpers_typeof = __webpack_require__(16); var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/objectSpread.js var objectSpread = __webpack_require__(9); var objectSpread_default = /*#__PURE__*/__webpack_require__.n(objectSpread); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/objectWithoutProperties.js var objectWithoutProperties = __webpack_require__(21); var objectWithoutProperties_default = /*#__PURE__*/__webpack_require__.n(objectWithoutProperties); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/classCallCheck.js var classCallCheck = __webpack_require__(4); var classCallCheck_default = /*#__PURE__*/__webpack_require__.n(classCallCheck); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/createClass.js var createClass = __webpack_require__(5); var createClass_default = /*#__PURE__*/__webpack_require__.n(createClass); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js var possibleConstructorReturn = __webpack_require__(6); var possibleConstructorReturn_default = /*#__PURE__*/__webpack_require__.n(possibleConstructorReturn); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/getPrototypeOf.js var getPrototypeOf = __webpack_require__(7); var getPrototypeOf_default = /*#__PURE__*/__webpack_require__.n(getPrototypeOf); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/inherits.js var inherits = __webpack_require__(8); var inherits_default = /*#__PURE__*/__webpack_require__.n(inherits); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/assertThisInitialized.js var assertThisInitialized = __webpack_require__(1); var assertThisInitialized_default = /*#__PURE__*/__webpack_require__.n(assertThisInitialized); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/defineProperty.js var defineProperty = __webpack_require__(2); var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/toConsumableArray.js var toConsumableArray = __webpack_require__(12); var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray); // EXTERNAL MODULE: ../node_modules/draft-js/dist/Draft.css var Draft = __webpack_require__(40); // EXTERNAL MODULE: ./assets/scss/_base.scss var _base = __webpack_require__(42); // EXTERNAL MODULE: external "react" var external_react_ = __webpack_require__(0); var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_); // CONCATENATED MODULE: ./languages/en.js /* harmony default export */ var en = ({ base: { remove: 'Remove', cancel: 'Cancel', confirm: 'Confirm', inert: 'Insert', width: 'Width', height: 'Height' }, controls: { clear: 'Clear', undo: 'Undo', redo: 'Redo', fontSize: 'Font Size', color: 'Color', textColor: 'Text', tempColors: 'Temp Colors', backgroundColor: 'Background', bold: 'Bold', lineHeight: 'Line Height', letterSpacing: 'Letter Spacing', textIndent: 'Text Indent', increaseIndent: 'Increase Indent', decreaseIndent: 'Decrease Indent', italic: 'Italic', underline: 'Underline', strikeThrough: 'Strike Through', fontFamily: 'Font Family', textAlign: 'Text Alignment', alignLeft: 'Left Alignment', alignCenter: 'Center Alignment', alignRight: 'Right Alignment', alignJustify: 'Justify Alignment', floatLeft: 'Left Float', floatRight: 'Right Float', superScript: 'Super Script', subScript: 'Sub Script', removeStyles: 'Remove Styles', headings: 'Headings', header: 'Header', normal: 'Normal', orderedList: 'Ordered List', unorderedList: 'Unordered List', blockQuote: 'Quote', code: 'Code', link: 'Link', unlink: 'Unlink', hr: 'Horizontal Line', media: 'Media', mediaLibirary: 'Media Library', emoji: 'Emoji', fullscreen: 'Fullscreen', exitFullscreen: 'Exit Fullscreen' }, linkEditor: { inputPlaceHolder: 'Input link URL', inputWithEnterPlaceHolder: 'Input link URL and press Enter', openInNewWindow: 'Open in new window', removeLink: 'Remove Link' }, audioPlayer: { title: 'Play Audio' }, videoPlayer: { title: 'Play Video', embedTitle: 'Embed Media' }, media: { image: 'Image', video: 'Video', audio: 'Audio', embed: 'Embed' } }); // CONCATENATED MODULE: ./languages/zh.js /* harmony default export */ var zh = ({ base: { remove: '删除', cancel: '取消', confirm: '确定', inert: '插入', width: '宽度', height: '高度' }, controls: { clear: '清除内容', undo: '撤销', redo: '重做', fontSize: '字号', lineHeight: '行高', letterSpacing: '字间距', textIndent: '段落缩进', increaseIndent: '增加缩进', decreaseIndent: '减少缩进', border: '边框', color: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', tempColors: '临时颜色', bold: '加粗', italic: '斜体', underline: '下划线', strikeThrough: '删除线', fontFamily: '字体', textAlign: '文本对齐', alignLeft: '居左', alignCenter: '居中', alignRight: '居右', alignJustify: '两端', floatLeft: '左浮动', floatRight: '右浮动', superScript: '上标', subScript: '下标', removeStyles: '清除样式', headings: '标题', header: '标题', normal: '常规', orderedList: '有序列表', unorderedList: '无序列表', blockQuote: '引用', code: '代码', link: '链接', unlink: '清除链接', hr: '水平线', media: '媒体', mediaLibirary: '媒体库', emoji: '小表情', fullscreen: '全屏', exitFullscreen: '退出全屏' }, linkEditor: { inputPlaceHolder: '输入链接地址', inputWithEnterPlaceHolder: '输入链接地址并回车', openInNewWindow: '在新窗口打开', removeLink: '移除链接' }, audioPlayer: { title: '播放音频文件' }, videoPlayer: { title: '播放视频文件', embedTitle: '嵌入式媒体' }, media: { image: '图像', video: '视频', audio: '音频', embed: '嵌入式媒体' } }); // CONCATENATED MODULE: ./languages/zh-hant.js /* harmony default export */ var zh_hant = ({ base: { remove: '刪除', cancel: '取消', confirm: '確定', inert: '插入', width: '宽度', height: '高度' }, controls: { clear: '清除内容', undo: '撤銷', redo: '重做', fontSize: '字號', color: '顏色', textColor: '文字顏色', backgroundColor: '背景顏色', tempColors: '臨時顏色', bold: '加粗', lineHeight: '行高', letterSpacing: '字間距', textIndent: '段落縮進', increaseIndent: '增加縮進', decreaseIndent: '减少縮進', border: '邊框', italic: '斜體', underline: '下劃線', strikeThrough: '刪除線', fontFamily: '字體', textAlign: '文本對齊', alignLeft: '居左', alignCenter: '居中', alignRight: '居右', alignJustify: '兩端對齊', floatLeft: '左浮動', floatRight: '右浮動', superScript: '上標', subScript: '下標', removeStyles: '清除样式', headings: '標題', header: '標題', normal: '常規', orderedList: '有序列表', unorderedList: '無序列表', blockQuote: '引用', code: '代碼', link: '鏈接', unlink: '清除鏈接', hr: '水平线', media: '媒體', mediaLibirary: '媒體库', emoji: '小表情', fullscreen: '全熒幕', exitFullscreen: '退出全熒幕' }, linkEditor: { inputPlaceHolder: '輸入鏈接地址', inputWithEnterPlaceHolder: '輸入鏈接地址並回車', openInNewWindow: '在新窗口打開', removeLink: '移除鏈接' }, audioPlayer: { title: '播放音頻文件' }, videoPlayer: { title: '播放視頻文件', embedTitle: '嵌入式媒體' }, media: { image: '圖像', video: '視頻', audio: '音頻', embed: '嵌入式媒體' } }); // CONCATENATED MODULE: ./languages/pl.js /* harmony default export */ var pl = ({ base: { remove: 'Usuń', cancel: 'Anuluj', confirm: 'Potwierdź', inert: 'Wstaw', width: 'Szerokość', height: 'Wysokość' }, controls: { clear: 'Wyczyść', undo: 'Cofnij', redo: 'Przywróć', fontSize: 'Wielkość', color: 'Kolor', textColor: 'Kolor tekstu', tempColors: 'Kolory', backgroundColor: 'Tło', bold: 'Pogrubienie', lineHeight: 'Wysokość linii', letterSpacing: 'Odstęp znaków', textIndent: 'Wcięcie tekstu', increaseIndent: 'Zwiększ wcięcie', decreaseIndent: 'Zmniejsz wcięcie', italic: 'Italiki', underline: 'Podkreślenie', strikeThrough: 'Przekreślenie', fontFamily: 'Czcionka', textAlign: 'Wyrównanie tekstu', alignLeft: 'Do lewej', alignCenter: 'Wycentruj', alignRight: 'Do prawej', alignJustify: 'Wyjustuj', floatLeft: 'Do lewej', floatRight: 'Do prawej', superScript: 'Superskrypt', subScript: 'Subskrypt', removeStyles: 'Usuń stylowanie', headings: 'Nagłówki', header: 'Nagłówek', normal: 'Normalny', orderedList: 'Lista uporządkowana', unorderedList: 'Lista nieuporządkowana', blockQuote: 'Cytat', code: 'Kod', link: 'Link', unlink: 'Usuń link', hr: 'Linia pozioma', media: 'Media', mediaLibirary: 'Biblioteka mediów', emoji: 'Emoji' }, linkEditor: { inputPlaceHolder: 'Adres URL', inputWithEnterPlaceHolder: 'Wpisz adres URL i naciśnij Enter', openInNewWindow: 'Otwórz w nowym oknie', removeLink: 'Usuń link' }, audioPlayer: { title: 'Odtwórz audio' }, videoPlayer: { title: 'Odtwórz wideo', embedTitle: 'Tytuł' }, media: { image: 'Obraz', video: 'Wideo', audio: 'Audio', embed: 'Obiekt osadzony' } }); // CONCATENATED MODULE: ./languages/index.js /* harmony default export */ var languages = ({ 'en': en, 'zh': zh, 'zh-hant': zh_hant, 'pl': pl }); // EXTERNAL MODULE: external "braft-finder" var external_braft_finder_ = __webpack_require__(17); var external_braft_finder_default = /*#__PURE__*/__webpack_require__.n(external_braft_finder_); // EXTERNAL MODULE: external "braft-utils" var external_braft_utils_ = __webpack_require__(3); // EXTERNAL MODULE: external "draft-js" var external_draft_js_ = __webpack_require__(10); // EXTERNAL MODULE: external "immutable" var external_immutable_ = __webpack_require__(13); var external_immutable_default = /*#__PURE__*/__webpack_require__.n(external_immutable_); // CONCATENATED MODULE: ./configs/keybindings.js // TODO // 允许自定义的快捷键设置 /* harmony default export */ var keybindings = (function (customKeyBindingFn) { return function (event) { if (event.keyCode === 83 && (external_draft_js_["KeyBindingUtil"].hasCommandModifier(event) || external_draft_js_["KeyBindingUtil"].isCtrlKeyCommand(event))) { return 'braft-save'; } if (customKeyBindingFn) { return customKeyBindingFn(event) || Object(external_draft_js_["getDefaultKeyBinding"])(event); } return Object(external_draft_js_["getDefaultKeyBinding"])(event); }; }); // CONCATENATED MODULE: ./configs/props.js /* harmony default export */ var configs_props = ({ language: 'zh', controls: ['undo', 'redo', 'separator', 'font-size', 'line-height', 'letter-spacing', 'separator', 'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator', 'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator', 'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator', 'media', 'link', 'table', 'split', 'hr', 'separator', 'clear', 'separator', 'fullscreen'], excludeControls: [], extendControls: [], extendAtomics: [], componentBelowControlBar: null, media: { pasteImage: true, imagePasteLimit: 5, image: true, video: true, audio: true, uploadFn: null, validateFn: null, onBeforeDeselect: null, onDeselect: null, onBeforeSelect: null, onSelect: null, onBeforeRemove: null, onRemove: null, onCancel: null, onFileSelect: null, onBeforeInsert: null, onInsert: null, onChange: null, accepts: { image: 'image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg', video: 'video/mp4', audio: 'audio/mp3' }, externals: { audio: true, video: true, image: true, embed: true } }, imageControls: ['float-left', 'float-right', 'align-left', 'align-center', 'align-right', 'link', 'size', 'remove'], colors: ['#000000', '#333333', '#666666', '#999999', '#cccccc', '#ffffff', '#61a951', '#16a085', '#07a9fe', '#003ba5', '#8e44ad', '#f32784', '#c0392b', '#d35400', '#f39c12', '#fdda00'], colorPicker: null, colorPickerTheme: 'dark', colorPickerAutoHide: true, codeTabIndents: 2, textAligns: ['left', 'center', 'right', 'justify'], textBackgroundColor: true, defaultLinkTarget: '', letterSpacings: [0, 1, 2, 3, 4, 5, 6], lineHeights: [1, 1.2, 1.5, 1.75, 2, 2.5, 3, 4], fontSizes: [12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 48, 56, 64, 72, 96, 120, 144], fontFamilies: [{ name: 'Araial', family: 'Arial, Helvetica, sans-serif' }, { name: 'Georgia', family: 'Georgia, serif' }, { name: 'Impact', family: 'Impact, serif' }, { name: 'Monospace', family: '"Courier New", Courier, monospace' }, { name: 'Tahoma', family: 'tahoma, arial, "Hiragino Sans GB", 宋体, sans-serif' }], converts: { unitExportFn: function unitExportFn(value, type) { return type === 'line-height' ? value : "".concat(value, "px"); } }, emojis: ['🤣', '🙌', '💚', '💛', '👏', '😉', '💯', '💕', '💞', '💘', '💙', '💝', '🖤', '💜', '❤️', '😍', '😻', '💓', '💗', '😋', '😇', '😂', '😹', '😘', '💖', '😁', '😀', '🤞', '😲', '😄', '😊', '👍', '😌', '😃', '😅', '✌️', '🤗', '💋', '😗', '😽', '😚', '🤠', '😙', '😺', '👄', '😸', '😏', '😼', '👌', '😎', '😆', '😛', '🙏', '🤝', '🙂', '🤑', '😝', '😐', '😑', '🤤', '😤', '🙃', '🤡', '😶', '😪', '😴', '😵', '😓', '👊', '😦', '😷', '🤐', '😜', '🤓', '👻', '😥', '🙄', '🤔', '🤒', '🙁', '😔', '😯', '☹️', '☠️', '😰', '😩', '😖', '😕', '😒', '😣', '😢', '😮', '😿', '🤧', '😫', '🤥', '😞', '😬', '👎', '💀', '😳', '😨', '🤕', '🤢', '😱', '😭', '😠', '😈', '😧', '💔', '😟', '🙀', '💩', '👿', '😡', '😾', '🖕'], stripPastedStyles: false, triggerChangeOnMount: true, className: '', style: {}, controlBarClassName: '', controlBarStyle: {}, contentClassName: '', contentStyle: {}, draftProps: {}, hooks: {}, onChange: null, onFocus: null, onBlur: null, onTab: null, onDelete: null, onSave: null }); // EXTERNAL MODULE: ../node_modules/draft-js/lib/getFragmentFromSelection.js var getFragmentFromSelection = __webpack_require__(22); var getFragmentFromSelection_default = /*#__PURE__*/__webpack_require__.n(getFragmentFromSelection); // EXTERNAL MODULE: external "draftjs-utils" var external_draftjs_utils_ = __webpack_require__(23); // CONCATENATED MODULE: ./configs/handlers.js var handlers_keyCommandHandlers = function keyCommandHandlers(command, editorState, editor) { if (editor.editorProps.handleKeyCommand && editor.editorProps.handleKeyCommand(command, editorState, editor) === 'handled') { return 'handled'; } if (command === 'braft-save') { editor.editorProps.onSave && editor.editorProps.onSave(editorState); return 'handled'; } var _editor$editorProps = editor.editorProps, controls = _editor$editorProps.controls, excludeControls = _editor$editorProps.excludeControls; var allowIndent = (controls.indexOf('text-indent') !== 0 || controls.find(function (item) { return item.key === 'text-indent'; })) && excludeControls.indexOf('text-indent') === -1; var cursorStart = editorState.getSelection().getStartOffset(); var cursorEnd = editorState.getSelection().getEndOffset(); var cursorIsAtFirst = cursorStart === 0 && cursorEnd === 0; if (command === 'backspace') { if (editor.editorProps.onDelete && editor.editorProps.onDelete(editorState) === false) { return 'handled'; } var blockType = external_braft_utils_["ContentUtils"].getSelectionBlockType(editorState); if (allowIndent && cursorIsAtFirst && blockType !== 'code-block') { editor.setValue(external_braft_utils_["ContentUtils"].decreaseSelectionIndent(editorState)); } } if (command === 'tab') { var _blockType = external_braft_utils_["ContentUtils"].getSelectionBlockType(editorState); if (_blockType === 'code-block') { editor.setValue(external_braft_utils_["ContentUtils"].insertText(editorState, ' '.repeat(editor.editorProps.codeTabIndents))); return 'handled'; } else if (_blockType !== 'atomic' && allowIndent && cursorIsAtFirst) { editor.setValue(external_braft_utils_["ContentUtils"].increaseSelectionIndent(editorState)); return 'handled'; } } var nextEditorState = external_braft_utils_["ContentUtils"].handleKeyCommand(editorState, command); if (nextEditorState) { editor.setValue(nextEditorState); return 'handled'; } return 'not-handled'; }; var handlers_returnHandlers = function returnHandlers(event, editorState, editor) { if (editor.editorProps.handleReturn && editor.editorProps.handleReturn(event, editorState, editor) === 'handled') { return 'handled'; } var currentBlock = external_braft_utils_["ContentUtils"].getSelectionBlock(editorState); var currentBlockType = currentBlock.getType(); if (currentBlockType === 'unordered-list-item' || currentBlockType === 'ordered-list-item') { if (currentBlock.getLength() === 0) { editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBlockType(editorState, 'unstyled')); return 'handled'; } return 'not-handled'; } else if (currentBlockType === 'code-block') { if (event.which === 13 && (event.getModifierState('Shift') || event.getModifierState('Alt') || event.getModifierState('Control'))) { editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBlockType(editorState, 'unstyled')); return 'handled'; } return 'not-handled'; } else if (currentBlockType === 'blockquote') { if (event.which === 13) { if (event.getModifierState('Shift') || event.getModifierState('Alt') || event.getModifierState('Control')) { event.which = 0; } else { editor.setValue(external_draft_js_["RichUtils"].insertSoftNewline(editorState)); return 'handled'; } } } var nextEditorState = Object(external_draftjs_utils_["handleNewLine"])(editorState, event); if (nextEditorState) { editor.setValue(nextEditorState); return 'handled'; } return 'not-handled'; }; var beforeInputHandlers = function beforeInputHandlers(chars, editorState, editor) { if (editor.editorProps.handleBeforeInput && editor.editorProps.handleBeforeInput(chars, editorState, editor) === 'handled') { return 'handled'; } return 'not-handled'; }; var handlers_compositionStartHandler = function compositionStartHandler(_, editor) { var editorState = editor.state.editorState; var selectedBlocks = external_braft_utils_["ContentUtils"].getSelectedBlocks(editorState); if (selectedBlocks && selectedBlocks.length > 1) { var nextEditorState = external_draft_js_["EditorState"].push(editorState, external_draft_js_["Modifier"].removeRange(editorState.getCurrentContent(), editorState.getSelection(), 'backward'), 'remove-range'); editor.setValue(nextEditorState); } }; var handlers_dropHandlers = function dropHandlers(selectionState, dataTransfer, editor) { if (editor.editorProps.readOnly || editor.editorProps.disabled) { return 'handled'; } if (window && window.__BRAFT_DRAGING__IMAGE__) { var nextEditorState = external_draft_js_["EditorState"].forceSelection(editor.state.editorState, selectionState); nextEditorState = external_braft_utils_["ContentUtils"].insertMedias(nextEditorState, [window.__BRAFT_DRAGING__IMAGE__.mediaData]); nextEditorState = external_braft_utils_["ContentUtils"].removeBlock(nextEditorState, window.__BRAFT_DRAGING__IMAGE__.block, nextEditorState.getSelection()); window.__BRAFT_DRAGING__IMAGE__ = null; editor.lockOrUnlockEditor(true); editor.setValue(nextEditorState); return 'handled'; } else if (!dataTransfer || !dataTransfer.getText()) { return 'handled'; } return 'not-handled'; }; var handlers_handleFiles = function handleFiles(files, editor) { var _editor$constructor$d = objectSpread_default()({}, editor.constructor.defaultProps.media, editor.editorProps.media), pasteImage = _editor$constructor$d.pasteImage, imagePasteLimit = _editor$constructor$d.imagePasteLimit; pasteImage && files.slice(0, imagePasteLimit).forEach(function (file) { file && file.type.indexOf('image') > -1 && editor.braftFinder.uploadImage(file, function (image) { editor.isLiving && editor.setValue(external_braft_utils_["ContentUtils"].insertMedias(editor.state.editorState, [image])); }); }); if (files[0] && files[0].type.indexOf('image') > -1 && pasteImage) { return 'handled'; } return 'not-handled'; }; var droppedFilesHandlers = function droppedFilesHandlers(selectionState, files, editor) { if (editor.editorProps.handleDroppedFiles && editor.editorProps.handleDroppedFiles(selectionState, files, editor) === 'handled') { return 'handled'; } return handlers_handleFiles(files, editor); }; var pastedFilesHandlers = function pastedFilesHandlers(files, editor) { if (editor.editorProps.handlePastedFiles && editor.editorProps.handlePastedFiles(files, editor) === 'handled') { return 'handled'; } return handlers_handleFiles(files, editor); }; var handlers_copyHandlers = function copyHandlers(event, editor) { var blockMap = getFragmentFromSelection_default()(editor.state.editorState); if (blockMap && blockMap.toArray) { try { var tempContentState = external_draft_js_["ContentState"].createFromBlockArray(blockMap.toArray()); var tempEditorState = external_draft_js_["EditorState"].createWithContent(tempContentState); var clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData; tempEditorState.setConvertOptions(editor.state.editorState.convertOptions); clipboardData.setData('text/html', tempEditorState.toHTML()); clipboardData.setData('text/plain', tempEditorState.toText()); event.preventDefault(); } catch (error) { console.warn(error); } } }; var handlers_pastedTextHandlers = function pastedTextHandlers(text, html, editorState, editor) { if (editor.editorProps.handlePastedText && editor.editorProps.handlePastedText(text, html, editorState, editor) === 'handled') { return 'handled'; } if (!html || editor.editorProps.stripPastedStyles) { return false; } var tempColors = external_braft_utils_["ColorUtils"].detectColorsFromHTMLString(html); editor.setState({ tempColors: toConsumableArray_default()(editor.state.tempColors).concat(toConsumableArray_default()(tempColors)).filter(function (item) { return editor.editorProps.colors.indexOf(item) === -1; }).filter(function (item, index, array) { return array.indexOf(item) === index; }) }, function () { editor.setValue(external_braft_utils_["ContentUtils"].insertHTML(editorState, html, 'paste')); }); return 'handled'; }; // CONCATENATED MODULE: ./helpers/extension.js // TODO // - block-style和atomic类型的扩展支持 var extension_extensionControls = []; var extension_extensionDecorators = []; var extension_propInterceptors = []; var extension_extensionBlockRenderMaps = []; var extension_extensionBlockRendererFns = []; var extensionInlineStyleMaps = []; var extension_extensionInlineStyleFns = []; var extensionEntities = []; var inlineStyleImporters = []; var inlineStyleExporters = []; var blockImporters = []; var blockExporters = []; var filterByEditorId = function filterByEditorId(items, editorId) { if (!editorId) { return items.filter(function (item) { return !item.includeEditors; }).map(function (item) { return item.data; }); } return items.map(function (item) { if (!item.includeEditors && !item.excludeEditors) { return item.data; } if (item.includeEditors) { return item.includeEditors.indexOf(editorId) !== -1 ? item.data : false; } if (item.excludeEditors) { return item.excludeEditors.indexOf(editorId) !== -1 ? false : item.data; } return false; }).filter(function (item) { return item; }); }; var getPropInterceptors = function getPropInterceptors(editorId) { return filterByEditorId(extension_propInterceptors, editorId); }; var getExtensionControls = function getExtensionControls(editorId) { return filterByEditorId(extension_extensionControls, editorId); }; var getExtensionDecorators = function getExtensionDecorators(editorId) { return filterByEditorId(extension_extensionDecorators, editorId, 'decorators'); }; var getExtensionBlockRenderMaps = function getExtensionBlockRenderMaps(editorId) { return filterByEditorId(extension_extensionBlockRenderMaps, editorId); }; var getExtensionBlockRendererFns = function getExtensionBlockRendererFns(editorId) { return filterByEditorId(extension_extensionBlockRendererFns, editorId); }; var getExtensionInlineStyleMap = function getExtensionInlineStyleMap(editorId) { var inlineStyleMap = {}; filterByEditorId(extensionInlineStyleMaps, editorId).forEach(function (item) { inlineStyleMap[item.inlineStyleName] = item.styleMap; }); return inlineStyleMap; }; var getExtensionInlineStyleFns = function getExtensionInlineStyleFns(editorId) { return filterByEditorId(extension_extensionInlineStyleFns, editorId); }; var compositeStyleImportFn = function compositeStyleImportFn(styleImportFn, editorId) { return function (nodeName, node, style) { filterByEditorId(inlineStyleImporters, editorId).forEach(function (styleImporter) { if (styleImporter.importer && styleImporter.importer(nodeName, node)) { style = style.add(styleImporter.inlineStyleName); } }); return styleImportFn ? styleImportFn(nodeName, node, style) : style; }; }; var compositeStyleExportFn = function compositeStyleExportFn(styleExportFn, editorId) { return function (style) { style = style.toUpperCase(); var result = styleExportFn ? styleExportFn(style) : undefined; if (result) { return result; } filterByEditorId(inlineStyleExporters, editorId).find(function (item) { if (item.inlineStyleName === style) { result = item.exporter; return true; } }); return result; }; }; var compositeEntityImportFn = function compositeEntityImportFn(entityImportFn, editorId) { return function (nodeName, node, createEntity, source) { var result = entityImportFn ? entityImportFn(nodeName, node, createEntity, source) : null; if (result) { return result; } filterByEditorId(extensionEntities, editorId).find(function (entityItem) { var matched = entityItem.importer ? entityItem.importer(nodeName, node, source) : null; matched && (result = createEntity(entityItem.entityType, matched.mutability || 'MUTABLE', matched.data || {})); return !!matched; }); return result; }; }; var compositeEntityExportFn = function compositeEntityExportFn(entityExportFn, editorId) { return function (entity, originalText) { var result = entityExportFn ? entityExportFn(entity, originalText) : undefined; if (result) { return result; } var entityType = entity.type.toUpperCase(); filterByEditorId(extensionEntities, editorId).find(function (entityItem) { if (entityItem.entityType === entityType) { result = entityItem.exporter ? entityItem.exporter(entity, originalText) : undefined; return true; } }); return result; }; }; var compositeBlockImportFn = function compositeBlockImportFn(blockImportFn, editorId) { return function (nodeName, node, source) { var result = blockImportFn ? blockImportFn(nodeName, node, source) : null; if (result) { return result; } filterByEditorId(blockImporters, editorId).find(function (blockImporter) { var matched = blockImporter.importer ? blockImporter.importer(nodeName, node, source) : undefined; matched && (result = matched); return !!matched; }); return result; }; }; var compositeBlockExportFn = function compositeBlockExportFn(blockExportFn, editorId) { return function (contentState, block) { var result = blockExportFn ? blockExportFn(contentState, block) : null; if (result) { return result; } filterByEditorId(blockExporters, editorId).find(function (blockExporter) { var matched = blockExporter.exporter ? blockExporter.exporter(contentState, block) : undefined; matched && (result = matched); return !!matched; }); return result; }; }; var extension_useExtension = function useExtension(extension) { if (extension instanceof Array) { extension.forEach(useExtension); return false; } if (!extension || !extension.type || typeof extension.type !== 'string') { return false; } var includeEditors = extension.includeEditors, excludeEditors = extension.excludeEditors; if (extension.type === 'control') { extension_extensionControls.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: extension.control }); } else if (extension.type === 'inline-style') { var inlineStyleName = extension.name.toUpperCase(); if (extension.control) { extension_extensionControls.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: objectSpread_default()({ key: inlineStyleName, type: 'inline-style', command: inlineStyleName }, extension.control) }); } if (extension.style) { extensionInlineStyleMaps.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { inlineStyleName: inlineStyleName, styleMap: extension.style } }); } if (extension.styleFn) { extension_extensionInlineStyleFns.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { inlineStyleName: inlineStyleName, styleFn: extension.styleFn } }); } if (extension.importer) { inlineStyleImporters.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { inlineStyleName: inlineStyleName, importer: extension.importer } }); } inlineStyleExporters.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { inlineStyleName: inlineStyleName, exporter: extension.exporter ? extension.exporter(extension) : external_react_default.a.createElement("span", { style: extension.style }) } }); } else if (extension.type === 'block-style') {// TODO } else if (extension.type === 'entity') { var entityType = extension.name.toUpperCase(); if (extension.control) { extension_extensionControls.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: typeof extension.control === 'function' ? extension.control : objectSpread_default()({ key: entityType, type: 'entity', command: entityType, data: { mutability: extension.mutability || 'MUTABLE', data: extension.data || {} } }, extension.control) }); } extensionEntities.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { entityType: entityType, importer: extension.importer, exporter: extension.exporter } }); extension_extensionDecorators.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { type: 'entity', decorator: { key: entityType, component: extension.component } } }); } else if (extension.type === 'block') { var blockType = extension.name; if (extension.renderMap) { extension_extensionBlockRenderMaps.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { blockType: blockType, renderMap: extension.renderMap } }); } if (extension.rendererFn) { extension_extensionBlockRendererFns.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { blockType: blockType, rendererFn: extension.rendererFn } }); } if (extension.importer) { blockImporters.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { blockType: blockType, importer: extension.importer } }); } if (extension.exporter) { blockExporters.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { blockType: blockType, exporter: extension.exporter } }); } } else if (extension.type === 'atomic') {// TODO } else if (extension.type === 'decorator') { var decorator = extension.decorator; if (decorator && decorator.strategy && decorator.component) { extension_extensionDecorators.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { type: 'strategy', decorator: decorator } }); } else if (decorator && decorator.getDecorations) { extension_extensionDecorators.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: { type: 'class', decorator: decorator } }); } } else if (extension.type === 'prop-interception') { extension_propInterceptors.push({ includeEditors: includeEditors, excludeEditors: excludeEditors, data: extension.interceptor }); } }; var createExtensibleEditor = function createExtensibleEditor(BraftEditor) { BraftEditor.use = extension_useExtension; return BraftEditor; }; // CONCATENATED MODULE: ./renderers/block/blockRenderMap.js /* harmony default export */ var block_blockRenderMap = (function (props, blockRenderMap) { var customBlockRenderMap = Object(external_immutable_["Map"])({ 'atomic': { element: '' }, 'code-block': { element: 'code', wrapper: external_react_default.a.createElement("pre", { className: "braft-code-block" }) } }); var extensionBlockRenderMaps = getExtensionBlockRenderMaps(props.editorId); extensionBlockRenderMaps.forEach(function (item) { if (typeof item.renderMap === 'function') { customBlockRenderMap = customBlockRenderMap.merge(item.renderMap(props)); } else if (item.renderMap instanceof external_immutable_["Map"]) { customBlockRenderMap = customBlockRenderMap.merge(item.renderMap); } }); if (blockRenderMap && blockRenderMap instanceof external_immutable_["Map"]) { customBlockRenderMap = customBlockRenderMap.merge(blockRenderMap); } customBlockRenderMap = external_draft_js_["DefaultDraftBlockRenderMap"].merge(customBlockRenderMap); return customBlockRenderMap; }); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/extends.js var helpers_extends = __webpack_require__(11); var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends); // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/slicedToArray.js var slicedToArray = __webpack_require__(24); var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray); // EXTERNAL MODULE: ./renderers/atomics/Image/style.scss var Image_style = __webpack_require__(45); // EXTERNAL MODULE: ./components/common/Switch/style.scss var Switch_style = __webpack_require__(46); // CONCATENATED MODULE: ./components/common/Switch/index.jsx /* harmony default export */ var Switch = (function (props) { var active = props.active, _onClick = props.onClick, className = props.className; return external_react_default.a.createElement("div", { onClick: function onClick() { return _onClick(); }, className: 'bf-switch ' + className + (active ? ' active' : '') }); }); // CONCATENATED MODULE: ./configs/controls.js /* harmony default export */ var configs_controls = (function (lang, editor) { return [{ key: 'undo', title: lang.controls.undo, text: external_react_default.a.createElement("i", { className: "bfi-undo" }), type: 'editor-method', command: 'undo' }, { key: 'redo', title: lang.controls.redo, text: external_react_default.a.createElement("i", { className: "bfi-redo" }), type: 'editor-method', command: 'redo' }, { key: 'remove-styles', title: lang.controls.removeStyles, text: external_react_default.a.createElement("i", { className: "bfi-format_clear" }), type: 'editor-method', command: 'removeSelectionInlineStyles' }, { key: 'hr', title: lang.controls.hr, text: external_react_default.a.createElement("i", { className: "bfi-hr" }), type: 'editor-method', command: 'insertHorizontalLine' }, { key: 'bold', title: lang.controls.bold, text: external_react_default.a.createElement("i", { className: "bfi-bold" }), type: 'inline-style', command: 'bold' }, { key: 'italic', title: lang.controls.italic, text: external_react_default.a.createElement("i", { className: "bfi-italic" }), type: 'inline-style', command: 'italic' }, { key: 'underline', title: lang.controls.underline, text: external_react_default.a.createElement("i", { className: "bfi-underlined" }), type: 'inline-style', command: 'underline' }, { key: 'strike-through', title: lang.controls.strikeThrough, text: external_react_default.a.createElement("i", { className: "bfi-strikethrough" }), type: 'inline-style', command: 'strikethrough' }, { key: 'superscript', title: lang.controls.superScript, text: external_react_default.a.createElement("i", { className: "bfi-superscript" }), type: 'inline-style', command: 'superscript' }, { key: 'subscript', title: lang.controls.subScript, text: external_react_default.a.createElement("i", { className: "bfi-subscript" }), type: 'inline-style', command: 'subscript' }, { key: 'headings', title: lang.controls.headings, type: 'headings' }, { key: 'blockquote', title: lang.controls.blockQuote, text: external_react_default.a.createElement("i", { className: "bfi-quote" }), type: 'block-type', command: 'blockquote' }, { key: 'code', title: lang.controls.code, text: external_react_default.a.createElement("i", { className: "bfi-code" }), type: 'block-type', command: 'code-block' }, { key: 'list-ul', title: lang.controls.unorderedList, text: external_react_default.a.createElement("i", { className: "bfi-list" }), type: 'block-type', command: 'unordered-list-item' }, { key: 'list-ol', title: lang.controls.orderedList, text: external_react_default.a.createElement("i", { className: "bfi-list-numbered" }), type: 'block-type', command: 'ordered-list-item' }, { key: 'link', title: lang.controls.link, type: 'link' }, { key: 'text-color', title: lang.controls.color, type: 'text-color' }, { key: 'line-height', title: lang.controls.lineHeight, type: 'line-height' }, { key: 'letter-spacing', title: lang.controls.letterSpacing, type: 'letter-spacing' }, { key: 'text-indent', title: lang.controls.textIndent, type: 'text-indent' }, { key: 'font-size', title: lang.controls.fontSize, type: 'font-size' }, { key: 'font-family', title: lang.controls.fontFamily, type: 'font-family' }, { key: 'text-align', title: lang.controls.textAlign, type: 'text-align' }, { key: 'media', title: lang.controls.media, text: external_react_default.a.createElement("i", { className: "bfi-media" }), type: 'media' }, { key: 'emoji', title: lang.controls.emoji, text: external_react_default.a.createElement("i", { className: "bfi-emoji" }), type: 'emoji' }, { key: 'clear', title: lang.controls.clear, text: external_react_default.a.createElement("i", { className: "bfi-clear_all" }), type: 'editor-method', command: 'clearEditorContent' }, { key: 'fullscreen', title: editor.state.isFullscreen ? lang.controls.exitFullscreen : lang.controls.fullscreen, text: external_react_default.a.createElement("i", { className: editor.state.isFullscreen ? 'bfi-fullscreen-exit' : 'bfi-fullscreen' }), type: 'editor-method', command: 'toggleFullscreen' }, { key: 'modal', type: 'modal' }, { key: 'button', type: 'button' }, { key: 'dropdown', type: 'dropdown' }, { key: 'component', type: 'component' }]; }); var imageControlItems = { 'float-left': { text: external_react_default.a.createElement("span", { "data-float": "left" }, "\uE91E"), command: 'setImageFloat|left' }, 'float-right': { text: external_react_default.a.createElement("span", { "data-float": "right" }, "\uE914"), command: 'setImageFloat|right' }, 'align-left': { text: external_react_default.a.createElement("span", { "data-align": "left" }, "\uE027"), command: 'setImageAlignment|left' }, 'align-center': { text: external_react_default.a.createElement("span", { "data-align": "center" }, "\uE028"), command: 'setImageAlignment|center' }, 'align-right': { text: external_react_default.a.createElement("span", { "data-align": "right" }, "\uE029"), command: 'setImageAlignment|right' }, 'size': { text: external_react_default.a.createElement("span", null, "\uE3C2"), command: 'toggleSizeEditor' }, 'link': { text: external_react_default.a.createElement("span", null, "\uE91A"), command: 'toggleLinkEditor' }, 'remove': { text: external_react_default.a.createElement("span", null, "\uE9AC"), command: 'removeImage' } }; // CONCATENATED MODULE: ./renderers/atomics/Image/index.jsx var Image_Image = /*#__PURE__*/ function (_React$Component) { inherits_default()(Image, _React$Component); function Image() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, Image); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Image)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { toolbarVisible: false, toolbarOffset: 0, linkEditorVisible: false, sizeEditorVisible: false, tempLink: null, tempWidth: null, tempHeight: null }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDragStart", function () { if (_this.props.editor.editorProps.readOnly || _this.props.editor.editorProps.disabled) { return false; } window.__BRAFT_DRAGING__IMAGE__ = { block: _this.props.block, mediaData: objectSpread_default()({ type: 'IMAGE' }, _this.props.mediaData) }; _this.setState({ toolbarVisible: false }, function () { _this.unlockEditor(); }); return true; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDragEnd", function () { window.__BRAFT_DRAGING__IMAGE__ = null; return false; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "executeCommand", function (command) { if (typeof command === 'string') { var _command$split = command.split('|'), _command$split2 = slicedToArray_default()(_command$split, 2), method = _command$split2[0], param = _command$split2[1]; _this[method] && _this[method](param); } else if (typeof command === 'function') { command(_this.props.block, _this.props.editorState); } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeImage", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block)); _this.unlockEditor(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleLinkEditor", function () { _this.setState({ linkEditorVisible: !_this.state.linkEditorVisible, sizeEditorVisible: false }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleSizeEditor", function () { _this.setState({ linkEditorVisible: false, sizeEditorVisible: !_this.state.sizeEditorVisible }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleLinkInputKeyDown", function (e) { if (e.keyCode === 13) { _this.confirmImageLink(); } else { return; } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageLink", function (e) { _this.setState({ tempLink: e.currentTarget.value }); return; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "confirmImageLink", function () { var link = _this.state.tempLink; if (link !== null) { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaData(_this.props.editorState, _this.props.entityKey, { link: link })); window.setImmediate(_this.props.editor.forceRender); } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleSizeInputKeyDown", function (e) { if (e.keyCode === 13) { _this.confirmImageSize(); } else { return; } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageWidth", function (_ref) { var currentTarget = _ref.currentTarget; var value = currentTarget.value; value && !isNaN(value) && (value = value + 'px'); _this.setState({ tempWidth: value }); return; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageHeight", function (_ref2) { var currentTarget = _ref2.currentTarget; var value = currentTarget.value; value && !isNaN(value) && (value = value + 'px'); _this.setState({ tempHeight: value }); return; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "confirmImageSize", function () { var _this$state = _this.state, width = _this$state.tempWidth, height = _this$state.tempHeight; var newImageSize = {}; width !== null && (newImageSize.width = width); height !== null && (newImageSize.height = height); _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaData(_this.props.editorState, _this.props.entityKey, newImageSize)); window.setImmediate(_this.props.editor.forceRender); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageFloat", function (float) { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaPosition(_this.props.editorState, _this.props.block, { float: float })); _this.unlockEditor(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageAlignment", function (alignment) { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaPosition(_this.props.editorState, _this.props.block, { alignment: alignment })); _this.unlockEditor(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "showToolbar", function (event) { if (_this.props.editor.editorProps.readOnly || _this.props.editor.editorProps.disabled) { return false; } event.preventDefault(); if (!_this.state.toolbarVisible) { _this.setState({ toolbarVisible: true }, function () { _this.lockEditor(); _this.setState({ toolbarOffset: _this.calcToolbarOffset() }); }); } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hideToolbar", function (event) { event.preventDefault(); _this.setState({ toolbarVisible: false }, function () { _this.unlockEditor(); _this.props.editor.requestFocus(); }); }); return _this; } createClass_default()(Image, [{ key: "render", value: function render() { var _this2 = this; var _this$props = this.props, mediaData = _this$props.mediaData, language = _this$props.language, imageControls = _this$props.imageControls; var _this$state2 = this.state, toolbarVisible = _this$state2.toolbarVisible, toolbarOffset = _this$state2.toolbarOffset, linkEditorVisible = _this$state2.linkEditorVisible, sizeEditorVisible = _this$state2.sizeEditorVisible; var blockData = this.props.block.getData(); var float = blockData.get('float'); var alignment = blockData.get('alignment'); var url = mediaData.url, link = mediaData.link, link_target = mediaData.link_target, width = mediaData.width, height = mediaData.height, meta = mediaData.meta; var imageStyles = {}; var clearFix = false; if (float) { alignment = null; } else if (alignment === 'left') { imageStyles.float = 'left'; clearFix = true; } else if (alignment === 'right') { imageStyles.float = 'right'; clearFix = true; } else if (alignment === 'center') { imageStyles.textAlign = 'center'; } else { imageStyles.float = 'left'; clearFix = true; } var renderedControlItems = imageControls.map(function (item, index) { if (typeof item === 'string' && imageControlItems[item]) { return external_react_default.a.createElement("a", { className: item === 'link' && link ? 'active' : '', key: index, href: "javascript:void(0);", onClick: function onClick() { return _this2.executeCommand(imageControlItems[item].command); } }, imageControlItems[item].text); } else if (item && (item.render || item.text)) { return item.render ? item.render(mediaData) : external_react_default.a.createElement("a", { key: index, href: "javascript:void(0);", onClick: function onClick() { return item.onClick && _this2.executeCommand(item.onClick); } }, item.text); } else { return null; } }); return external_react_default.a.createElement("div", { className: "bf-media" }, external_react_default.a.createElement("div", { style: imageStyles, draggable: true, onMouseEnter: this.showToolbar, onMouseMove: this.showToolbar, onMouseLeave: this.hideToolbar, onDragStart: this.handleDragStart, onDragEnd: this.handleDragEnd, ref: function ref(instance) { return _this2.mediaEmbederInstance = instance; }, className: "bf-image" }, toolbarVisible ? external_react_default.a.createElement("div", { style: { marginLeft: toolbarOffset }, ref: function ref(instance) { return _this2.toolbarElement = instance; }, "data-float": float, "data-align": alignment, className: "bf-media-toolbar" }, linkEditorVisible ? external_react_default.a.createElement("div", { className: "bf-image-link-editor" }, external_react_default.a.createElement("div", { className: "editor-input-group" }, external_react_default.a.createElement("input", { type: "text", placeholder: language.linkEditor.inputWithEnterPlaceHolder, onKeyDown: this.handleLinkInputKeyDown, onChange: this.setImageLink, defaultValue: link }), external_react_default.a.createElement("button", { type: "button", onClick: this.confirmImageLink }, language.base.confirm)), external_react_default.a.createElement("div", { className: "switch-group" }, external_react_default.a.createElement(Switch, { active: link_target === '_blank', onClick: function onClick() { return _this2.setImageLinkTarget(link_target); } }), external_react_default.a.createElement("label", null, language.linkEditor.openInNewWindow))) : null, sizeEditorVisible ? external_react_default.a.createElement("div", { className: "bf-image-size-editor" }, external_react_default.a.createElement("div", { className: "editor-input-group" }, external_react_default.a.createElement("input", { type: "text", placeholder: language.base.width, onKeyDown: this.handleSizeInputKeyDown, onChange: this.setImageWidth, defaultValue: width }), external_react_default.a.createElement("input", { type: "text", placeholder: language.base.height, onKeyDown: this.handleSizeInputKeyDown, onChange: this.setImageHeight, defaultValue: height }), external_react_default.a.createElement("button", { type: "button", onClick: this.confirmImageSize }, language.base.confirm))) : null, renderedControlItems, external_react_default.a.createElement("i", { style: { marginLeft: toolbarOffset * -1 }, className: "bf-media-toolbar-arrow" })) : null, external_react_default.a.createElement("img", extends_default()({ ref: function ref(instance) { return _this2.imageElement = instance; }, src: url, width: width, height: height }, meta))), clearFix && external_react_default.a.createElement("div", { className: "clearfix", style: { clear: 'both', height: 0, lineHeight: 0, float: 'none' } })); } }, { key: "lockEditor", value: function lockEditor() { this.props.editor.lockOrUnlockEditor(true); } }, { key: "unlockEditor", value: function unlockEditor() { this.props.editor.lockOrUnlockEditor(false); } }, { key: "calcToolbarOffset", value: function calcToolbarOffset() { if (!this.props.containerNode) { return 0; } var viewRect = this.props.containerNode.querySelector('.bf-content').getBoundingClientRect(); var toolbarRect = this.toolbarElement.getBoundingClientRect(); var imageRect = this.imageElement.getBoundingClientRect(); var right = viewRect.right - (imageRect.right - imageRect.width / 2 + toolbarRect.width / 2); var left = imageRect.left + imageRect.width / 2 - toolbarRect.width / 2 - viewRect.left; if (right < 10) { return right - 10; } else if (left < 10) { return left * -1 + 10; } else { return 0; } } }, { key: "setImageLinkTarget", value: function setImageLinkTarget(link_target) { link_target = link_target === '_blank' ? '' : '_blank'; this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaData(this.props.editorState, this.props.entityKey, { link_target: link_target })); window.setImmediate(this.props.editor.forceRender); } }]); return Image; }(external_react_default.a.Component); // EXTERNAL MODULE: ./renderers/atomics/Video/style.scss var Video_style = __webpack_require__(47); // CONCATENATED MODULE: ./components/common/StaticContainer/index.jsx var StaticContainer_default = /*#__PURE__*/ function (_React$Component) { inherits_default()(_default, _React$Component); function _default() { classCallCheck_default()(this, _default); return possibleConstructorReturn_default()(this, getPrototypeOf_default()(_default).apply(this, arguments)); } createClass_default()(_default, [{ key: "shouldComponentUpdate", value: function shouldComponentUpdate() { return false; } }, { key: "render", value: function render() { return external_react_default.a.createElement("div", null, this.props.children); } }]); return _default; }(external_react_default.a.Component); // CONCATENATED MODULE: ./renderers/atomics/Video/index.jsx var Video_Video = /*#__PURE__*/ function (_React$Component) { inherits_default()(Video, _React$Component); function Video() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, Video); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Video)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { toolbarVisible: false }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeVideo", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "showToolbar", function () { _this.setState({ toolbarVisible: true }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hideToolbar", function () { _this.setState({ toolbarVisible: false }); }); return _this; } createClass_default()(Video, [{ key: "render", value: function render() { var toolbarVisible = this.state.toolbarVisible; var mediaData = this.props.mediaData; var url = mediaData.url, meta = mediaData.meta; return external_react_default.a.createElement("div", { className: "bf-video-wrap", onMouseOver: this.showToolbar, onMouseLeave: this.hideToolbar }, external_react_default.a.createElement(StaticContainer_default, null, external_react_default.a.createElement("video", { controls: true, src: url, poster: meta ? meta.poster || '' : '' })), toolbarVisible ? external_react_default.a.createElement("div", { className: "bf-media-toolbar" }, external_react_default.a.createElement("a", { onClick: this.removeVideo }, "\uE9AC")) : null); } }]); return Video; }(external_react_default.a.Component); // EXTERNAL MODULE: ./renderers/atomics/Audio/style.scss var Audio_style = __webpack_require__(48); // CONCATENATED MODULE: ./renderers/atomics/Audio/index.jsx var Audio_Audio = /*#__PURE__*/ function (_React$Component) { inherits_default()(Audio, _React$Component); function Audio() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, Audio); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Audio)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { toolbarVisible: false }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeAudio", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "showToolbar", function () { _this.setState({ toolbarVisible: true }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hideToolbar", function () { _this.setState({ toolbarVisible: false }); }); return _this; } createClass_default()(Audio, [{ key: "render", value: function render() { var toolbarVisible = this.state.toolbarVisible; var mediaData = this.props.mediaData; var url = mediaData.url; return external_react_default.a.createElement("div", { className: "bf-audio", onMouseOver: this.showToolbar, onMouseLeave: this.hideToolbar }, external_react_default.a.createElement(StaticContainer_default, null, external_react_default.a.createElement("audio", { controls: true, src: url })), toolbarVisible ? external_react_default.a.createElement("div", { className: "bf-media-toolbar" }, external_react_default.a.createElement("a", { onClick: this.removeAudio }, "\uE9AC")) : null); } }]); return Audio; }(external_react_default.a.Component); // EXTERNAL MODULE: ./renderers/atomics/Embed/style.scss var Embed_style = __webpack_require__(49); // CONCATENATED MODULE: ./renderers/atomics/Embed/index.jsx var Embed_Embed = /*#__PURE__*/ function (_React$Component) { inherits_default()(Embed, _React$Component); function Embed() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, Embed); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Embed)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { toolbarVisible: false }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeEmbed", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "showToolbar", function () { _this.setState({ toolbarVisible: true }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hideToolbar", function () { _this.setState({ toolbarVisible: false }); }); return _this; } createClass_default()(Embed, [{ key: "render", value: function render() { var toolbarVisible = this.state.toolbarVisible; var mediaData = this.props.mediaData; var url = mediaData.url; return external_react_default.a.createElement("div", { className: "bf-embed", onMouseOver: this.showToolbar, onMouseLeave: this.hideToolbar }, external_react_default.a.createElement(StaticContainer_default, null, external_react_default.a.createElement("div", { className: "bf-embed-player", dangerouslySetInnerHTML: { __html: url } })), toolbarVisible ? external_react_default.a.createElement("div", { className: "bf-media-toolbar" }, external_react_default.a.createElement("a", { onClick: this.removeEmbed }, "\uE9AC")) : null); } }]); return Embed; }(external_react_default.a.Component); // EXTERNAL MODULE: ./renderers/atomics/HorizontalLine/style.scss var HorizontalLine_style = __webpack_require__(50); // CONCATENATED MODULE: ./renderers/atomics/HorizontalLine/index.jsx var HorizontalLine_HorizontalLine = /*#__PURE__*/ function (_React$Component) { inherits_default()(HorizontalLine, _React$Component); function HorizontalLine() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, HorizontalLine); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(HorizontalLine)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeHorizontalLine", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block)); }); return _this; } createClass_default()(HorizontalLine, [{ key: "render", value: function render() { return external_react_default.a.createElement("div", { className: "bf-hr" }, external_react_default.a.createElement("div", { className: "bf-media-toolbar" }, external_react_default.a.createElement("a", { onClick: this.removeHorizontalLine }, "\uE9AC"))); } }]); return HorizontalLine; }(external_react_default.a.Component); // CONCATENATED MODULE: ./renderers/block/blockRendererFn.js var blockRendererFn_getAtomicBlockComponent = function getAtomicBlockComponent(superProps) { return function (props) { var entityKey = props.block.getEntityAt(0); if (!entityKey) { return null; } var entity = props.contentState.getEntity(entityKey); var mediaData = entity.getData(); var mediaType = entity.getType(); var mediaProps = objectSpread_default()({}, superProps, { block: props.block, mediaData: mediaData, entityKey: entityKey }); if (mediaType === 'IMAGE') { return external_react_default.a.createElement(Image_Image, mediaProps); } else if (mediaType === 'AUDIO') { return external_react_default.a.createElement(Audio_Audio, mediaProps); } else if (mediaType === 'VIDEO') { return external_react_default.a.createElement(Video_Video, mediaProps); } else if (mediaType === 'EMBED') { return external_react_default.a.createElement(Embed_Embed, mediaProps); } else if (mediaType === 'HR') { return external_react_default.a.createElement(HorizontalLine_HorizontalLine, mediaProps); } if (superProps.extendAtomics) { var atomics = superProps.extendAtomics; for (var i = 0; i < atomics.length; i++) { if (mediaType === atomics[i].type) { var Component = atomics[i].component; return external_react_default.a.createElement(Component, mediaProps); } } } return null; }; }; /* harmony default export */ var block_blockRendererFn = (function (superProps, customBlockRendererFn) { return function (block) { var blockType = block.getType(); var blockRenderer = null; if (customBlockRendererFn) { blockRenderer = customBlockRendererFn(block, superProps) || null; } if (blockRenderer) { return blockRenderer; } var extensionBlockRendererFns = getExtensionBlockRendererFns(superProps.editorId); extensionBlockRendererFns.find(function (item) { if (item.blockType === blockType || item.blockType instanceof RegExp && item.blockType.test(blockType)) { blockRenderer = item.rendererFn ? item.rendererFn(superProps) : null; return true; } }); if (blockRenderer) { return blockRenderer; } if (blockType === 'atomic') { blockRenderer = { component: blockRendererFn_getAtomicBlockComponent(superProps), editable: false }; } return blockRenderer; }; }); // CONCATENATED MODULE: ./renderers/block/blockStyleFn.js /* harmony default export */ var block_blockStyleFn = (function (customBlockStyleFn) { return function (block) { var blockAlignment = block.getData() && block.getData().get('textAlign'); var blockIndent = block.getData() && block.getData().get('textIndent'); var blockFloat = block.getData() && block.getData().get('float'); var result = ''; if (blockAlignment) { result = "bfa-".concat(blockAlignment); } if (blockIndent && blockIndent !== 0) { result += " bftd-".concat(blockIndent); } if (blockFloat) { result += " bff-".concat(blockFloat); } if (customBlockStyleFn) { result += customBlockStyleFn(block) || ''; } return result; }; }); // CONCATENATED MODULE: ./renderers/inline/inlineStyleMap.js /* harmony default export */ var inlineStyleMap = (function (props) { var customStyleMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var extensionInlineStyleMap = getExtensionInlineStyleMap(props.editorId); return objectSpread_default()({ 'SUPERSCRIPT': { position: 'relative', top: '-8px', fontSize: '11px' }, 'SUBSCRIPT': { position: 'relative', bottom: '-8px', fontSize: '11px' } }, extensionInlineStyleMap, customStyleMap); }); // CONCATENATED MODULE: ./renderers/inline/inlineStyleFn.js var getStyleValue = function getStyleValue(style) { return style.split('-')[1]; }; /* harmony default export */ var inlineStyleFn = (function (props, options) { return function (styles, block) { var output = {}; var fontFamilies = options.fontFamilies, unitExportFn = options.unitExportFn, customStyleFn = options.customStyleFn; var extensionInlineStyleFns = getExtensionInlineStyleFns(props.editorId); extensionInlineStyleFns.forEach(function (item) { output = item.styleFn ? item.styleFn(styles, block, output) : output; }); output = customStyleFn ? customStyleFn(styles, block, output) : {}; styles.forEach(function (style) { if (style.indexOf('COLOR-') === 0) { output.color = '#' + getStyleValue(style); } else if (style.indexOf('BGCOLOR-') === 0) { output.backgroundColor = '#' + getStyleValue(style); } else if (style.indexOf('FONTSIZE-') === 0) { output.fontSize = unitExportFn(getStyleValue(style), 'font-size', 'editor'); } else if (style.indexOf('LINEHEIGHT-') === 0) { output.lineHeight = unitExportFn(getStyleValue(style), 'line-height', 'editor'); } else if (style.indexOf('LETTERSPACING-') === 0) { output.letterSpacing = unitExportFn(getStyleValue(style), 'letter-spacing', 'editor'); } else if (style.indexOf('TEXTINDENT-') === 0) { output.textIndent = unitExportFn(getStyleValue(style), 'text-indent', 'editor'); } else if (style.indexOf('FONTFAMILY-') === 0) { output.fontFamily = (fontFamilies.find(function (item) { return item.name.toUpperCase() === getStyleValue(style); }) || {}).family || ''; } }); return output; }; }); // EXTERNAL MODULE: ../node_modules/draft-js-multidecorators/index.js var draft_js_multidecorators = __webpack_require__(18); var draft_js_multidecorators_default = /*#__PURE__*/__webpack_require__.n(draft_js_multidecorators); // CONCATENATED MODULE: ./renderers/decorators/Link/index.jsx /* harmony default export */ var Link = (function (props) { var children = props.children, entityKey = props.entityKey, contentState = props.contentState; var _contentState$getEnti = contentState.getEntity(entityKey).getData(), href = _contentState$getEnti.href, target = _contentState$getEnti.target; return external_react_default.a.createElement("span", { className: "bf-link-wrap" }, external_react_default.a.createElement("a", { onClick: function onClick(event) { return viewLink(event, href); }, className: "bf-link", href: href, target: target }, children)); }); var viewLink = function viewLink(event, link) { if (event.getModifierState('Shift')) { var tempLink = document.createElement('a'); tempLink.href = link; tempLink.target = '_blank'; tempLink.click(); } }; // CONCATENATED MODULE: ./renderers/decorators/index.js var KEY_SEPARATOR = '-'; draft_js_multidecorators_default.a.prototype.getDecorations = function (block, contentState) { var decorations = Array(block.getText().length).fill(null); this.decorators.forEach(function (decorator, i) { decorator.getDecorations(block, contentState).forEach(function (key, offset) { if (!key) { return; } key = i + KEY_SEPARATOR + key; decorations[offset] = key; }); }); return external_immutable_default.a.List(decorations); }; var builtinDecorators = [{ type: 'entity', decorator: { key: 'LINK', component: Link } }]; var createStrategy = function createStrategy(type) { return function (block, callback, contentState) { block.findEntityRanges(function (character) { var entityKey = character.getEntity(); return entityKey !== null && contentState.getEntity(entityKey).getType() === type; }, callback); }; }; /* harmony default export */ var decorators = (function (editorId) { var extensionDecorators = getExtensionDecorators(editorId); var entityDecorators = builtinDecorators.concat(toConsumableArray_default()(extensionDecorators.filter(function (item) { return item.type === 'entity'; }))); var strategyDecorators = extensionDecorators.filter(function (item) { return item.type === 'strategy'; }); var classDecorators = extensionDecorators.filter(function (item) { return item.type === 'class'; }); return new draft_js_multidecorators_default.a(toConsumableArray_default()(classDecorators.map(function (item) { return item.decorator; })).concat([// combine decorators created with strategy new external_draft_js_["CompositeDecorator"](strategyDecorators.map(function (item) { return item.decorator; })), // combine decorators for entities new external_draft_js_["CompositeDecorator"](entityDecorators.map(function (item) { return { strategy: createStrategy(item.decorator.key), component: item.decorator.component }; }))])); }); // CONCATENATED MODULE: ./renderers/index.js var getBlockRenderMap = block_blockRenderMap; var getBlockRendererFn = block_blockRendererFn; var getBlockStyleFn = block_blockStyleFn; var getCustomStyleMap = inlineStyleMap; var getCustomStyleFn = inlineStyleFn; var getDecorators = decorators; // EXTERNAL MODULE: ./components/business/ControlBar/style.scss var ControlBar_style = __webpack_require__(51); // EXTERNAL MODULE: ./components/business/LinkEditor/style.scss var LinkEditor_style = __webpack_require__(52); // EXTERNAL MODULE: ./components/common/DropDown/style.scss var DropDown_style = __webpack_require__(53); // CONCATENATED MODULE: ./helpers/responsive.js var resizeEventHandlers = []; var responsiveHelperInited = false; var debouce = false; /* harmony default export */ var responsive = ({ resolve: function resolve(eventHandler) { var id = external_braft_utils_["BaseUtils"].UniqueIndex(); resizeEventHandlers.push({ id: id, eventHandler: eventHandler }); return id; }, unresolve: function unresolve(id) { resizeEventHandlers = resizeEventHandlers.filter(function (item) { return item.id !== id; }); } }); if (!responsiveHelperInited) { window.addEventListener('resize', function (event) { clearTimeout(debouce); debouce = setTimeout(function () { resizeEventHandlers.map(function (item) { typeof item.eventHandler === 'function' && item.eventHandler(event); }); debouce = false; }, 100); }); responsiveHelperInited = true; } // CONCATENATED MODULE: ./components/common/DropDown/index.jsx var DropDown_DropDown = /*#__PURE__*/ function (_React$Component) { inherits_default()(DropDown, _React$Component); function DropDown() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, DropDown); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(DropDown)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "responsiveResolveId", null); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "dropDownHandlerElement", null); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "dropDownContentElement", null); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { active: false, offset: 0 }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "fixDropDownPosition", function () { var viewRect = _this.props.containerNode.getBoundingClientRect(); var handlerRect = _this.dropDownHandlerElement.getBoundingClientRect(); var contentRect = _this.dropDownContentElement.getBoundingClientRect(); var offset = 0; var right = handlerRect.right - handlerRect.width / 2 + contentRect.width / 2; var left = handlerRect.left + handlerRect.width / 2 - contentRect.width / 2; right = viewRect.right - right; left = left - viewRect.left; if (right < 10) { offset = right - 10; } else if (left < 10) { offset = left * -1 + 10; } if (offset !== _this.state.offset) { _this.setState({ offset: offset }); } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "registerClickEvent", function (event) { var autoHide = _this.props.autoHide; var active = _this.state.active; if (_this.dropDownContentElement.contains(event.target) || _this.dropDownHandlerElement.contains(event.target)) { return false; } autoHide && active && _this.hide(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggle", function () { _this.setState({ active: !_this.state.active }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "show", function () { _this.setState({ active: true }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hide", function () { _this.setState({ active: false }); }); return _this; } createClass_default()(DropDown, [{ key: "componentDidMount", value: function componentDidMount() { document.body.addEventListener('click', this.registerClickEvent); this.responsiveResolveId = responsive.resolve(this.fixDropDownPosition); } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(next) { if (!this.props.disabled && next.disabled) { this.hide(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevState) { if (!prevState.active && this.state.active) { this.fixDropDownPosition(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { document.body.removeEventListener('click', this.registerClickEvent); responsive.unresolve(this.responsiveResolveId); } }, { key: "render", value: function render() { var _this2 = this; var _this$state = this.state, active = _this$state.active, offset = _this$state.offset; var _this$props = this.props, caption = _this$props.caption, htmlCaption = _this$props.htmlCaption, title = _this$props.title, disabled = _this$props.disabled, showArrow = _this$props.showArrow, arrowActive = _this$props.arrowActive, className = _this$props.className, children = _this$props.children, theme = _this$props.theme; disabled && (active = false); theme === 'light' && (className = ' light-theme ' + className); return external_react_default.a.createElement("div", { className: 'bf-dropdown ' + (active ? 'active ' : '') + (disabled ? 'disabled ' : '') + className }, htmlCaption ? external_react_default.a.createElement("button", { type: "button", className: "dropdown-handler", "data-title": title, onClick: this.toggle, dangerouslySetInnerHTML: htmlCaption ? { __html: htmlCaption } : null, ref: function ref(instance) { return _this2.dropDownHandlerElement = instance; } }) : external_react_default.a.createElement("button", { type: "button", className: "dropdown-handler", "data-title": title, onClick: this.toggle, ref: function ref(instance) { return _this2.dropDownHandlerElement = instance; } }, external_react_default.a.createElement("span", null, caption), showArrow !== false ? external_react_default.a.createElement("i", { className: "bfi-drop-down" }) : null), external_react_default.a.createElement("div", { className: "dropdown-content", style: { marginLeft: offset }, ref: function ref(instance) { return _this2.dropDownContentElement = instance; } }, external_react_default.a.createElement("i", { style: { marginLeft: offset * -1 }, className: 'dropdown-arrow' + (arrowActive ? ' active' : '') }), external_react_default.a.createElement("div", { className: "dropdown-content-inner" }, children))); } }]); return DropDown; }(external_react_default.a.Component); // CONCATENATED MODULE: ./components/business/ControlGroup/index.jsx /* harmony default export */ var ControlGroup = (function (props) { if (external_react_default.a.Fragment) { return external_react_default.a.createElement(external_react_default.a.Fragment, null, props.children); } else { return external_react_default.a.createElement("div", { className: "control-item-group" }, props.children); } }); // CONCATENATED MODULE: ./components/business/LinkEditor/index.jsx var LinkEditor_LinkEditor = /*#__PURE__*/ function (_React$Component) { inherits_default()(LinkEditor, _React$Component); function LinkEditor(props) { var _this; classCallCheck_default()(this, LinkEditor); _this = possibleConstructorReturn_default()(this, getPrototypeOf_default()(LinkEditor).call(this, props)); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "dropDownInstance", null); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handeKeyDown", function (e) { if (e.keyCode === 13) { _this.handleConfirm(); e.preventDefault(); return false; } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "inputLink", function (e) { _this.setState({ href: e.currentTarget.value }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setTarget", function () { _this.setState({ target: _this.state.target === '_blank' ? '' : '_blank' }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCancel", function () { _this.dropDownInstance.hide(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleUnlink", function () { _this.dropDownInstance.hide(); _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLink(_this.props.editorState, false)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleConfirm", function () { var _this$state = _this.state, href = _this$state.href, target = _this$state.target; var hookReturns = _this.props.hooks('toggle-link', { href: href, target: target })({ href: href, target: target }); _this.dropDownInstance.hide(); _this.props.editor.requestFocus(); if (hookReturns === false) { return false; } if (hookReturns) { typeof hookReturns.href === 'string' && (href = hookReturns.href); typeof hookReturns.target === 'string' && (target = hookReturns.target); } _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLink(_this.props.editorState, href, target)); }); _this.state = { href: '', target: props.defaultLinkTarget || '' }; return _this; } createClass_default()(LinkEditor, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { var _ContentUtils$getSele = external_braft_utils_["ContentUtils"].getSelectionEntityData(nextProps.editorState, 'LINK'), href = _ContentUtils$getSele.href, target = _ContentUtils$getSele.target; this.setState({ href: href || '', target: typeof target === 'undefined' ? nextProps.defaultLinkTarget || '' : target || '' }); } }, { key: "render", value: function render() { var _this2 = this; var _this$state2 = this.state, href = _this$state2.href, target = _this$state2.target; var caption = external_react_default.a.createElement("i", { className: "bfi-link" }); var textSelected = !external_braft_utils_["ContentUtils"].isSelectionCollapsed(this.props.editorState) && external_braft_utils_["ContentUtils"].getSelectionBlockType(this.props.editorState) !== 'atomic'; return external_react_default.a.createElement(ControlGroup, null, external_react_default.a.createElement(DropDown_DropDown, { key: 0, caption: caption, title: this.props.language.controls.link, autoHide: true, containerNode: this.props.containerNode, showArrow: false, disabled: !textSelected, ref: function ref(instance) { return _this2.dropDownInstance = instance; }, className: 'control-item dropdown link-editor-dropdown' }, external_react_default.a.createElement("div", { className: "bf-link-editor" }, external_react_default.a.createElement("div", { className: "input-group" }, external_react_default.a.createElement("input", { type: "text", value: href, spellCheck: false, placeholder: this.props.language.linkEditor.inputPlaceHolder, onKeyDown: this.handeKeyDown, onChange: this.inputLink })), external_react_default.a.createElement("div", { className: "switch-group" }, external_react_default.a.createElement(Switch, { active: target === '_blank', onClick: this.setTarget }), external_react_default.a.createElement("label", null, this.props.language.linkEditor.openInNewWindow)), external_react_default.a.createElement("div", { className: "buttons" }, external_react_default.a.createElement("a", { onClick: this.handleUnlink, className: "primary button-remove-link pull-left", href: "javascript:void(0);" }, external_react_default.a.createElement("i", { className: "bfi-close" }), external_react_default.a.createElement("span", null, this.props.language.linkEditor.removeLink)), external_react_default.a.createElement("button", { type: "button", onClick: this.handleConfirm, className: "primary pull-right" }, this.props.language.base.confirm), external_react_default.a.createElement("button", { type: "button", onClick: this.handleCancel, className: "default pull-right" }, this.props.language.base.cancel)))), external_react_default.a.createElement("button", { key: 1, type: "button", "data-title": this.props.language.controls.unlink, className: "control-item button", onClick: this.handleUnlink, disabled: !textSelected || !href }, external_react_default.a.createElement("i", { className: "bfi-link-off" }))); } }]); return LinkEditor; }(external_react_default.a.Component); // EXTERNAL MODULE: ./components/business/Headings/style.scss var Headings_style = __webpack_require__(54); // CONCATENATED MODULE: ./configs/maps.js var maps_getHeadings = function getHeadings(lang) { return [{ key: 'header-one', title: lang.controls.header + ' 1', text: external_react_default.a.createElement("h1", null, lang.controls.header, " 1"), type: 'block-type', command: 'header-one' }, { key: 'header-two', title: lang.controls.header + ' 2', text: external_react_default.a.createElement("h2", null, lang.controls.header, " 2"), type: 'block-type', command: 'header-two' }, { key: 'header-three', title: lang.controls.header + ' 3', text: external_react_default.a.createElement("h3", null, lang.controls.header, " 3"), type: 'block-type', command: 'header-three' }, { key: 'header-four', title: lang.controls.header + ' 4', text: external_react_default.a.createElement("h4", null, lang.controls.header, " 4"), type: 'block-type', command: 'header-four' }, { key: 'header-five', title: lang.controls.header + ' 5', text: external_react_default.a.createElement("h5", null, lang.controls.header, " 5"), type: 'block-type', command: 'header-five' }, { key: 'header-six', title: lang.controls.header + ' 6', text: external_react_default.a.createElement("h6", null, lang.controls.header, " 6"), type: 'block-type', command: 'header-six' }, { key: 'unstyled', title: lang.controls.normal, text: lang.controls.normal, type: 'block-type', command: 'unstyled' }]; }; var blocks = { 'header-one': 'h1', 'header-two': 'h2', 'header-three': 'h3', 'header-four': 'h4', 'header-fiv': 'h5', 'header-six': 'h6', 'unstyled': 'p', 'blockquote': 'blockquote' }; // CONCATENATED MODULE: ./components/business/Headings/index.jsx /* harmony default export */ var Headings = (function (props) { var dropDownInstance = null; var headings = maps_getHeadings(props.language); var currentHeadingIndex = headings.findIndex(function (item) { return item.command === props.current; }); var caption = headings[currentHeadingIndex] ? headings[currentHeadingIndex].title : props.language.controls.normal; return external_react_default.a.createElement(DropDown_DropDown, { caption: caption, autoHide: true, containerNode: props.containerNode, title: props.language.controls.headings, arrowActive: currentHeadingIndex === 0, ref: function ref(instance) { return dropDownInstance = instance; }, className: 'control-item dropdown headings-dropdown' }, external_react_default.a.createElement("ul", { className: "menu" }, headings.map(function (item, index) { var isActive = props.current === item.command; return external_react_default.a.createElement("li", { key: index, className: 'menu-item' + (isActive ? ' active' : ''), onClick: function onClick() { props.onChange(item.command, item.type), dropDownInstance.hide(); } }, item.text); }))); }); // EXTERNAL MODULE: ./components/business/TextColor/style.scss var TextColor_style = __webpack_require__(55); // EXTERNAL MODULE: ./components/common/ColorPicker/style.scss var ColorPicker_style = __webpack_require__(56); // CONCATENATED MODULE: ./components/common/ColorPicker/index.jsx /* harmony default export */ var common_ColorPicker = (function (props) { return external_react_default.a.createElement("div", { className: "bf-colors-wrap" }, external_react_default.a.createElement("ul", { className: "bf-colors" }, props.presetColors.map(function (item, index) { var className = props.color && item.toLowerCase() === props.color.toLowerCase() ? 'color-item active' : 'color-item'; return external_react_default.a.createElement("li", { key: index, title: item, className: className, style: { color: item }, "data-color": item.replace('#', ''), onClick: function onClick(e) { props.onChange(e.currentTarget.dataset.color, true); } }); }))); }); // CONCATENATED MODULE: ./components/business/TextColor/index.jsx var TextColor_TextColor = /*#__PURE__*/ function (_React$Component) { inherits_default()(TextColor, _React$Component); function TextColor() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, TextColor); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(TextColor)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { colorType: 'color' }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "switchColorType", function (_ref) { var currentTarget = _ref.currentTarget; _this.setState({ colorType: currentTarget.dataset.type }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleColor", function (color, closePicker) { if (color) { var hookReturns = _this.props.hooks("toggle-text-".concat(_this.state.colorType), color)(color); if (hookReturns === false) { return false; } if (typeof hookReturns === 'string') { color = hookReturns; } if (_this.state.colorType === 'color') { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionColor(_this.props.editorState, color)); } else { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBackgroundColor(_this.props.editorState, color)); } } if (closePicker) { _this.dropDownInstance.hide(); _this.props.editor.requestFocus(); } }); return _this; } createClass_default()(TextColor, [{ key: "render", value: function render() { var _this2 = this; var captionStyle = {}; var currentColor = null; var colorType = this.state.colorType; var selectionStyles = this.props.editorState.getCurrentInlineStyle().toJS(); selectionStyles.forEach(function (style) { if (style.indexOf('COLOR-') === 0) { captionStyle.color = '#' + style.split('-')[1]; colorType === 'color' && (currentColor = captionStyle.color); } if (style.indexOf('BGCOLOR-') === 0) { captionStyle.backgroundColor = '#' + style.split('-')[1]; colorType === 'background-color' && (currentColor = captionStyle.backgroundColor); } }); var caption = external_react_default.a.createElement("i", { style: captionStyle, className: "bfi-text-color" }, external_react_default.a.createElement("span", { className: "path1" }), external_react_default.a.createElement("span", { className: "path2" })); var ColorPicker = this.props.colorPicker || common_ColorPicker; return external_react_default.a.createElement(DropDown_DropDown, { caption: caption, title: this.props.language.controls.color, showArrow: false, autoHide: this.props.autoHide, theme: this.props.theme, containerNode: this.props.containerNode, ref: function ref(instance) { return _this2.dropDownInstance = instance; }, className: 'control-item dropdown text-color-dropdown' }, external_react_default.a.createElement("div", { className: "bf-text-color-picker-wrap" }, external_react_default.a.createElement("div", { className: "bf-color-switch-buttons", style: this.props.enableBackgroundColor ? {} : { display: 'none' } }, external_react_default.a.createElement("button", { type: "button", "data-type": "color", className: colorType === 'color' ? 'active' : '', onClick: this.switchColorType }, this.props.language.controls.textColor), external_react_default.a.createElement("button", { type: "button", "data-type": "background-color", className: colorType === 'background-color' ? 'active' : '', onClick: this.switchColorType }, this.props.language.controls.backgroundColor)), external_react_default.a.createElement(ColorPicker, { width: 200, color: currentColor, disableAlpha: true, presetColors: this.props.colors, onChange: this.toggleColor }))); } }]); return TextColor; }(external_react_default.a.Component); // EXTERNAL MODULE: ./components/business/FontSize/style.scss var FontSize_style = __webpack_require__(57); // CONCATENATED MODULE: ./components/business/FontSize/index.jsx var FontSize_toggleFontSize = function toggleFontSize(event, props) { var fontSize = event.currentTarget.dataset.size; var hookReturns = props.hooks('toggle-font-size', fontSize)(fontSize); if (hookReturns === false) { return false; } if (!isNaN(fontSize)) { fontSize = hookReturns; } props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionFontSize(props.editorState, fontSize)); props.editor.requestFocus(); }; /* harmony default export */ var FontSize = (function (props) { var caption = null; var currentFontSize = null; var dropDownInstance = null; props.fontSizes.find(function (item) { if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'FONTSIZE-' + item)) { caption = item; currentFontSize = item; return true; } return false; }); return external_react_default.a.createElement(DropDown_DropDown, { autoHide: true, caption: caption || props.defaultCaption, containerNode: props.containerNode, title: props.language.controls.fontSize, ref: function ref(instance) { return dropDownInstance = instance; }, className: 'control-item dropdown bf-font-size-dropdown' }, external_react_default.a.createElement("ul", { className: "bf-font-sizes" }, props.fontSizes.map(function (item, index) { return external_react_default.a.createElement("li", { key: index, className: item === currentFontSize ? 'active' : null, "data-size": item, onClick: function onClick(event) { FontSize_toggleFontSize(event, props), dropDownInstance.hide(); } }, item); }))); }); // EXTERNAL MODULE: ./components/business/LineHeight/style.scss var LineHeight_style = __webpack_require__(58); // CONCATENATED MODULE: ./components/business/LineHeight/index.jsx var LineHeight_toggleLineHeight = function toggleLineHeight(event, props) { var lineHeight = event.currentTarget.dataset.size; var hookReturns = props.hooks('toggle-line-height', lineHeight)(lineHeight); if (hookReturns === false) { return false; } if (!isNaN(hookReturns)) { lineHeight = hookReturns; } props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLineHeight(props.editorState, lineHeight)); props.editor.requestFocus(); }; /* harmony default export */ var LineHeight = (function (props) { var caption = null; var currentLineHeight = null; var dropDownInstance = null; props.lineHeights.find(function (item) { if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'LINEHEIGHT-' + item)) { caption = item; currentLineHeight = item; return true; } return false; }); return external_react_default.a.createElement(DropDown_DropDown, { autoHide: true, caption: caption || props.defaultCaption, containerNode: props.containerNode, title: props.language.controls.lineHeight, ref: function ref(instance) { return dropDownInstance = instance; }, className: 'control-item dropdown bf-line-height-dropdown' }, external_react_default.a.createElement("ul", { className: "bf-line-heights" }, props.lineHeights.map(function (item, index) { return external_react_default.a.createElement("li", { key: index, className: item === currentLineHeight ? 'active' : null, "data-size": item, onClick: function onClick(event) { LineHeight_toggleLineHeight(event, props), dropDownInstance.hide(); } }, item); }))); }); // EXTERNAL MODULE: ./components/business/FontFamily/style.scss var FontFamily_style = __webpack_require__(59); // CONCATENATED MODULE: ./components/business/FontFamily/index.jsx var FontFamily_toggleFontFamily = function toggleFontFamily(event, props) { var fontFamilyName = event.currentTarget.dataset.name; var hookReturns = props.hooks('toggle-font-family', fontFamilyName)(fontFamilyName, props.fontFamilies); if (hookReturns === false) { return false; } if (typeof hookReturns === 'string') { fontFamilyName = hookReturns; } props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionFontFamily(props.editorState, fontFamilyName)); props.editor.requestFocus(); }; /* harmony default export */ var FontFamily = (function (props) { var caption = null; var currentIndex = null; var dropDownInstance = null; props.fontFamilies.find(function (item, index) { if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'FONTFAMILY-' + item.name)) { caption = item.name; currentIndex = index; return true; } return false; }); return external_react_default.a.createElement(DropDown_DropDown, { caption: caption || props.defaultCaption, containerNode: props.containerNode, title: props.language.controls.fontFamily, autoHide: true, arrowActive: currentIndex === 0, ref: function ref(instance) { return dropDownInstance = instance; }, className: 'control-item dropdown font-family-dropdown' }, external_react_default.a.createElement("ul", { className: "menu" }, props.fontFamilies.map(function (item, index) { return external_react_default.a.createElement("li", { key: index, className: 'menu-item ' + (index === currentIndex ? 'active' : ''), "data-name": item.name, onClick: function onClick(event) { FontFamily_toggleFontFamily(event, props), dropDownInstance.hide(); } }, external_react_default.a.createElement("span", { style: { fontFamily: item.family } }, item.name)); }))); }); // CONCATENATED MODULE: ./components/business/TextAlign/index.jsx var TextAlign_TextAlign = /*#__PURE__*/ function (_React$Component) { inherits_default()(TextAlign, _React$Component); function TextAlign() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, TextAlign); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(TextAlign)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { currentAlignment: undefined }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setAlignment", function (event) { var alignment = event.currentTarget.dataset.alignment; var hookReturns = _this.props.hooks('toggle-text-alignment', alignment)(alignment); if (_this.props.textAligns.indexOf(hookReturns) > -1) { alignment = hookReturns; } _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionAlignment(_this.props.editorState, alignment)); _this.props.editor.requestFocus(); }); return _this; } createClass_default()(TextAlign, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(next) { this.setState({ currentAlignment: external_braft_utils_["ContentUtils"].getSelectionBlockData(next.editorState, 'textAlign') }); } }, { key: "render", value: function render() { var _this2 = this; var textAlignmentTitles = [this.props.language.controls.alignLeft, this.props.language.controls.alignCenter, this.props.language.controls.alignRight, this.props.language.controls.alignJustify]; return external_react_default.a.createElement(ControlGroup, null, this.props.textAligns.map(function (item, index) { return external_react_default.a.createElement("button", { type: "button", key: index, "data-title": textAlignmentTitles[index], "data-alignment": item, className: 'control-item button ' + (item === _this2.state.currentAlignment ? 'active' : null), onClick: _this2.setAlignment }, external_react_default.a.createElement("i", { className: 'bfi-align-' + item })); })); } }]); return TextAlign; }(external_react_default.a.Component); // EXTERNAL MODULE: ./components/business/EmojiPicker/style.scss var EmojiPicker_style = __webpack_require__(60); // CONCATENATED MODULE: ./components/business/EmojiPicker/index.jsx var EmojiPicker_insertEmoji = function insertEmoji(event, props) { var emoji = event.currentTarget.dataset.emoji; var hookReturns = props.hooks('insert-emoji', emoji)(emoji); if (hookReturns === false) { return false; } if (typeof hookReturns === 'string') { emoji = hookReturns; } props.editor.setValue(external_braft_utils_["ContentUtils"].insertText(props.editorState, emoji)); props.editor.requestFocus(); }; /* harmony default export */ var EmojiPicker = (function (props) { return external_react_default.a.createElement(DropDown_DropDown, { caption: props.defaultCaption, autoHide: true, showArrow: false, containerNode: props.containerNode, title: props.language.controls.emoji, className: 'control-item dropdown bf-emoji-dropdown' }, external_react_default.a.createElement("div", { className: "bf-emojis-wrap" }, external_react_default.a.createElement("ul", { className: "bf-emojis" }, props.emojis.map(function (item, index) { return external_react_default.a.createElement("li", { key: index, "data-emoji": item, onClick: function onClick(event) { return EmojiPicker_insertEmoji(event, props); } }, item); })))); }); // EXTERNAL MODULE: ./components/business/LetterSpacing/style.scss var LetterSpacing_style = __webpack_require__(61); // CONCATENATED MODULE: ./components/business/LetterSpacing/index.jsx var LetterSpacing_toggleLetterSpacing = function toggleLetterSpacing(event, props) { var letterSpacing = event.currentTarget.dataset.size; var hookReturns = props.hooks('toggle-letter-spacing', letterSpacing)(letterSpacing); if (hookReturns === false) { return false; } if (!isNaN(hookReturns)) { letterSpacing = hookReturns; } props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLetterSpacing(props.editorState, letterSpacing)); props.editor.requestFocus(); }; /* harmony default export */ var LetterSpacing = (function (props) { var caption = null; var currentLetterSpacing = null; var dropDownInstance = null; props.letterSpacings.find(function (item) { if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'LETTERSPACING-' + item)) { caption = item; currentLetterSpacing = item; return true; } return false; }); return external_react_default.a.createElement(DropDown_DropDown, { autoHide: true, caption: caption || props.defaultCaption, containerNode: props.containerNode, title: props.language.controls.letterSpacing, ref: function ref(instance) { return dropDownInstance = instance; }, className: 'control-item dropdown bf-letter-spacing-dropdown' }, external_react_default.a.createElement("ul", { className: "bf-letter-spacings" }, props.letterSpacings.map(function (item, index) { return external_react_default.a.createElement("li", { key: index, className: item === currentLetterSpacing ? 'active' : null, "data-size": item, onClick: function onClick(event) { LetterSpacing_toggleLetterSpacing(event, props), dropDownInstance.hide(); } }, item); }))); }); // CONCATENATED MODULE: ./components/business/TextIndent/index.jsx var TextIndent_TextAlign = /*#__PURE__*/ function (_React$Component) { inherits_default()(TextAlign, _React$Component); function TextAlign() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, TextAlign); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(TextAlign)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", { currentIndent: 0 }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "increaseIndent", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].increaseSelectionIndent(_this.props.editorState)); _this.props.editor.requestFocus(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "decreaseIndent", function () { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].decreaseSelectionIndent(_this.props.editorState)); _this.props.editor.requestFocus(); }); return _this; } createClass_default()(TextAlign, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { this.setState({ currentIndent: external_braft_utils_["ContentUtils"].getSelectionBlockData(nextProps.editorState, 'textIndent') || 0 }); } }, { key: "render", value: function render() { var currentIndent = this.state.currentIndent; var language = this.props.language; return external_react_default.a.createElement(ControlGroup, null, external_react_default.a.createElement("button", { key: 0, type: "button", "data-title": language.controls.increaseIndent, disabled: currentIndent >= 6, className: "control-item button button-indent-increase".concat(currentIndent > 0 && currentIndent < 6 ? ' active' : ''), onClick: this.increaseIndent }, external_react_default.a.createElement("i", { className: 'bfi-indent-increase' })), external_react_default.a.createElement("button", { key: 1, type: "button", "data-title": language.controls.decreaseIndent, disabled: currentIndent <= 0, className: "control-item button button-indent-decrease", onClick: this.decreaseIndent }, external_react_default.a.createElement("i", { className: 'bfi-indent-decrease' }))); } }]); return TextAlign; }(external_react_default.a.Component); // EXTERNAL MODULE: ./components/common/Modal/style.scss var Modal_style = __webpack_require__(62); // EXTERNAL MODULE: external "react-dom" var external_react_dom_ = __webpack_require__(15); var external_react_dom_default = /*#__PURE__*/__webpack_require__.n(external_react_dom_); // CONCATENATED MODULE: ./components/common/Modal/index.jsx var Modal_Modal = /*#__PURE__*/ function (_React$Component) { inherits_default()(Modal, _React$Component); function Modal(props) { var _this; classCallCheck_default()(this, Modal); _this = possibleConstructorReturn_default()(this, getPrototypeOf_default()(Modal).call(this, props)); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleTransitionEnd", function () { if (!_this.rootElement || !_this.rootElement.classList) { return false; } if (!_this.rootElement.classList.contains('active')) { external_react_dom_default.a.unmountComponentAtNode(_this.rootElement) && _this.rootElement.parentNode.removeChild(_this.rootElement); } }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleMouseDown", function (event) { event.preventDefault(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCancel", function () { _this.props.closeOnCancel && _this.close(); _this.props.onCancel && _this.props.onCancel(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleConfirm", function () { _this.props.closeOnConfirm && _this.close(); _this.props.onConfirm && _this.props.onConfirm(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleMaskClick", function () { _this.props.closeOnBlur && _this.close(); _this.props.onBlue && _this.props.onBlue(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "close", function () { _this.unrenderComponent(); _this.props.onClose && _this.props.onClose(); }); _this.active = false; _this.componentId = 'BRAFT-MODAL-' + external_braft_utils_["BaseUtils"].UniqueIndex(); return _this; } createClass_default()(Modal, [{ key: "componentDidMount", value: function componentDidMount() { if (this.props.visible) { this.active = true; this.renderComponent(this.props); } } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(next) { if (this.props.visible && !next.visible) { this.unrenderComponent(); } else if (this.props.visible || next.visible) { this.active = true; this.renderComponent(next); } } }, { key: "render", value: function render() { return null; } }, { key: "unrenderComponent", value: function unrenderComponent() { this.active = false; this.activeId && window.clearImmediate(this.activeId); if (this.rootElement && this.rootElement.classList) { this.rootElement.classList.remove('active'); } } }, { key: "renderComponent", value: function renderComponent(props) { var _this2 = this; if (!this.active) { return false; } var title = props.title, className = props.className, width = props.width, height = props.height, children = props.children, component = props.component, confirmable = props.confirmable, showFooter = props.showFooter, showCancel = props.showCancel, showConfirm = props.showConfirm, showClose = props.showClose, cancelText = props.cancelText, confirmText = props.confirmText, bottomText = props.bottomText, language = props.language; typeof showCancel === 'undefined' && (showCancel = true); typeof showClose === 'undefined' && (showClose = true); typeof showConfirm === 'undefined' && (showConfirm = true); typeof showFooter === 'undefined' && (showFooter = true); var childComponent = external_react_default.a.createElement("div", { onMouseDown: this.handleMouseDown, className: 'bf-modal ' + (className || '') }, external_react_default.a.createElement("div", { className: "bf-modal-mask", onClick: this.handleMaskClick }), external_react_default.a.createElement("div", { onTransitionEnd: this.handleTransitionEnd, style: { width: width, height: height }, className: "bf-modal-content" }, external_react_default.a.createElement("div", { className: "bf-modal-header" }, external_react_default.a.createElement("h3", { className: "bf-modal-caption" }, title), showClose && external_react_default.a.createElement("button", { type: "button", onClick: this.close, className: "bf-modal-close-button" }, external_react_default.a.createElement("i", { className: "bfi-close" }))), external_react_default.a.createElement("div", { className: "bf-modal-body" }, children || component), showFooter ? external_react_default.a.createElement("div", { className: "bf-modal-footer" }, external_react_default.a.createElement("div", { className: "bf-modal-addon-text" }, bottomText), external_react_default.a.createElement("div", { className: "bf-modal-buttons" }, showCancel && external_react_default.a.createElement("button", { type: "button", onClick: this.handleCancel, className: "bf-modal-cancel" }, cancelText || language.base.cancel), showConfirm && external_react_default.a.createElement("button", { type: "button", onClick: this.handleConfirm, className: 'bf-modal-confirm ' + (!confirmable ? 'disabled' : '') }, confirmText || language.base.confirm))) : null)); this.rootElement = document.querySelector('#' + this.componentId); if (!this.rootElement) { this.rootElement = document.createElement('div'); this.rootElement.id = this.componentId; this.rootElement.className = 'bf-modal-root'; document.body.appendChild(this.rootElement); } external_react_dom_default.a.render(childComponent, this.rootElement); this.activeId = window.setImmediate(function () { _this2.rootElement.classList.add('active'); }); } }]); return Modal; }(external_react_default.a.Component); defineProperty_default()(Modal_Modal, "defaultProps", { showFooter: true, closeOnBlur: true }); var Modal_showModal = function showModal(props) { var hostNode = document.createElement('div'); hostNode.style.display = 'none'; document.body.appendChild(hostNode); props = objectSpread_default()({ visible: true, closeOnConfirm: true, closeOnCancel: true }, props); var close = function close() { external_react_dom_default.a.unmountComponentAtNode(hostNode) && hostNode.parentNode.removeChild(hostNode); }; var onConfirm = function onConfirm() { props.onConfirm && props.onConfirm(); }; var onCancel = function onCancel() { props.onCancel && props.onCancel(); }; var onClose = function onClose() { close(); props.onClose && props.onClose(); }; var modalInstance = external_react_dom_default.a.render(external_react_default.a.createElement(Modal_Modal, extends_default()({}, props, { onConfirm: onConfirm, onCancel: onCancel, onClose: onClose })), hostNode); modalInstance.destroy = close; modalInstance.update = modalInstance.renderComponent; return modalInstance; }; // CONCATENATED MODULE: ./components/business/ControlBar/index.jsx var commandHookMap = { 'inline-style': 'toggle-inline-style', 'block-type': 'change-block-type', 'editor-method': 'exec-editor-command' }; var mergeControls = function mergeControls(commonProps, builtControls, extensionControls, extendControls) { extensionControls = extensionControls.map(function (item) { return typeof item === 'function' ? item(commonProps) : item; }); extendControls = extendControls.map(function (item) { return typeof item === 'function' ? item(commonProps) : item; }); if (extensionControls.length === 0 && extendControls.length === 0) { return builtControls; } return builtControls.map(function (item) { return extendControls.find(function (subItem) { return subItem.replace === (item.key || item); }) || extensionControls.find(function (subItem) { return subItem.replace === (item.key || item); }) || item; }).concat(extensionControls.length ? 'separator' : '').concat(extensionControls.filter(function (item) { return !item.replace; })).concat(extendControls.filter(function (item) { return !item.replace; })); }; var ControlBar_ControlBar = /*#__PURE__*/ function (_React$Component) { inherits_default()(ControlBar, _React$Component); function ControlBar() { var _getPrototypeOf2; var _this; classCallCheck_default()(this, ControlBar); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(ControlBar)).call.apply(_getPrototypeOf2, [this].concat(args))); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "allControls", []); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "mediaLibiraryModal", null); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "extendedModals", {}); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "openBraftFinder", function () { if (!_this.props.braftFinder || !_this.props.braftFinder.ReactComponent) { return false; } if (_this.props.hooks('open-braft-finder')() === false) { return false; } var mediaProps = _this.props.media; var MediaLibrary = _this.props.braftFinder.ReactComponent; _this.mediaLibiraryModal = Modal_showModal({ title: _this.props.language.controls.mediaLibirary, language: _this.props.language, width: 640, showFooter: false, component: external_react_default.a.createElement(MediaLibrary, { accepts: mediaProps.accepts, onCancel: _this.closeBraftFinder, onInsert: _this.insertMedias, onChange: mediaProps.onChange, externals: mediaProps.externals, onBeforeSelect: _this.bindBraftFinderHook('select-medias'), onBeforeDeselect: _this.bindBraftFinderHook('deselect-medias'), onBeforeRemove: _this.bindBraftFinderHook('remove-medias'), onBeforeInsert: _this.bindBraftFinderHook('insert-medias'), onFileSelect: _this.bindBraftFinderHook('select-files') }) }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "bindBraftFinderHook", function (hookName) { return function () { return _this.props.hooks(hookName, arguments.length <= 0 ? undefined : arguments[0]).apply(void 0, arguments); }; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "insertMedias", function (medias) { _this.props.editor.setValue(external_braft_utils_["ContentUtils"].insertMedias(_this.props.editorState, medias)); _this.props.editor.requestFocus(); _this.props.media.onInsert && _this.props.media.onInsert(medias); _this.closeBraftFinder(); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "closeBraftFinder", function () { _this.props.media.onCancel && _this.props.media.onCancel(); _this.mediaLibiraryModal && _this.mediaLibiraryModal.close(); }); return _this; } createClass_default()(ControlBar, [{ key: "componentDidUpdate", value: function componentDidUpdate() { var _this2 = this; var language = this.props.language; this.allControls.forEach(function (item) { if (item.type === 'modal') { if (item.modal && item.modal.id && _this2.extendedModals[item.modal.id]) { _this2.extendedModals[item.modal.id].update(objectSpread_default()({}, item.modal, { language: language })); } } }); } }, { key: "getControlItemClassName", value: function getControlItemClassName(data) { var className = 'control-item button'; var type = data.type, command = data.command; if (type === 'inline-style' && external_braft_utils_["ContentUtils"].selectionHasInlineStyle(this.props.editorState, command)) { className += ' active'; } else if (type === 'block-type' && external_braft_utils_["ContentUtils"].getSelectionBlockType(this.props.editorState) === command) { className += ' active'; } else if (type === 'entity' && external_braft_utils_["ContentUtils"].getSelectionEntityType(this.props.editorState) === command) { className += ' active'; } return className; } }, { key: "applyControl", value: function applyControl(command, type) { var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var hookReturns = this.props.hooks(commandHookMap[type] || type, command)(command); if (hookReturns === false) { return false; } if (typeof hookReturns === 'string') { command = hookReturns; } if (type === 'inline-style') { this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionInlineStyle(this.props.editorState, command)); } else if (type === 'block-type') { this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBlockType(this.props.editorState, command)); } else if (type === 'entity') { this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionEntity(this.props.editorState, { type: command, mutability: data.mutability || 'MUTABLE', data: data.data || {} })); } else if (type === 'editor-method') { this.props.editor[command] && this.props.editor[command](); } } }, { key: "render", value: function render() { var _this3 = this; var _this$props = this.props, editor = _this$props.editor, editorId = _this$props.editorId, editorState = _this$props.editorState, className = _this$props.className, style = _this$props.style, controls = _this$props.controls, media = _this$props.media, extendControls = _this$props.extendControls, language = _this$props.language, hooks = _this$props.hooks, colors = _this$props.colors, colorPicker = _this$props.colorPicker, colorPickerTheme = _this$props.colorPickerTheme, colorPickerAutoHide = _this$props.colorPickerAutoHide, fontSizes = _this$props.fontSizes, fontFamilies = _this$props.fontFamilies, emojis = _this$props.emojis, containerNode = _this$props.containerNode, lineHeights = _this$props.lineHeights, letterSpacings = _this$props.letterSpacings, textAligns = _this$props.textAligns, textBackgroundColor = _this$props.textBackgroundColor, defaultLinkTarget = _this$props.defaultLinkTarget; var currentBlockType = external_braft_utils_["ContentUtils"].getSelectionBlockType(editorState); var commonProps = { editor: editor, editorId: editorId, editorState: editorState, language: language, containerNode: containerNode, hooks: hooks }; var renderedControls = []; var editorControls = configs_controls(language, editor); var extensionControls = getExtensionControls(editorId); var allControls = mergeControls(commonProps, controls, extensionControls, extendControls); this.allControls = allControls; return external_react_default.a.createElement("div", { className: "bf-controlbar ".concat(className || ''), style: style, onMouseDown: this.preventDefault }, allControls.map(function (item, index) { var itemKey = typeof item === 'string' ? item : item.key; if (typeof itemKey !== 'string') { return null; } if (renderedControls.indexOf(itemKey) > -1) { return null; } if (itemKey.toLowerCase() === 'separator') { return external_react_default.a.createElement("span", { key: index, className: "separator-line" }); } var controlItem = editorControls.find(function (subItem) { return subItem.key.toLowerCase() === itemKey.toLowerCase(); }); if (typeof item !== 'string') { controlItem = objectSpread_default()({}, controlItem, item); } if (!controlItem) { return null; } renderedControls.push(itemKey); if (controlItem.type === 'headings') { return external_react_default.a.createElement(Headings, extends_default()({ key: index, current: currentBlockType, onChange: function onChange(command) { return _this3.applyControl(command, 'block-type'); } }, commonProps)); } else if (controlItem.type === 'text-color') { return external_react_default.a.createElement(TextColor_TextColor, extends_default()({ key: index, colors: colors, colorPicker: colorPicker, theme: colorPickerTheme, autoHide: colorPickerAutoHide, enableBackgroundColor: textBackgroundColor }, commonProps)); } else if (controlItem.type === 'font-size') { return external_react_default.a.createElement(FontSize, extends_default()({ key: index, fontSizes: fontSizes, defaultCaption: controlItem.title }, commonProps)); } else if (controlItem.type === 'line-height') { return external_react_default.a.createElement(LineHeight, extends_default()({ key: index, lineHeights: lineHeights, defaultCaption: controlItem.title }, commonProps)); } else if (controlItem.type === 'letter-spacing') { return external_react_default.a.createElement(LetterSpacing, extends_default()({ key: index, letterSpacings: letterSpacings, defaultCaption: controlItem.title }, commonProps)); } else if (controlItem.type === 'text-indent') { return external_react_default.a.createElement(TextIndent_TextAlign, extends_default()({ key: index, defaultCaption: controlItem.title }, commonProps)); } else if (controlItem.type === 'font-family') { return external_react_default.a.createElement(FontFamily, extends_default()({ key: index, fontFamilies: fontFamilies, defaultCaption: controlItem.title }, commonProps)); } else if (controlItem.type === 'emoji') { return external_react_default.a.createElement(EmojiPicker, extends_default()({ key: index, emojis: emojis, defaultCaption: controlItem.text }, commonProps)); } else if (controlItem.type === 'link') { return external_react_default.a.createElement(LinkEditor_LinkEditor, extends_default()({ key: index, defaultLinkTarget: defaultLinkTarget }, commonProps)); } else if (controlItem.type === 'text-align') { return external_react_default.a.createElement(TextAlign_TextAlign, extends_default()({ key: index, textAligns: textAligns }, commonProps)); } else if (controlItem.type === 'media') { if (!media.image && !media.video && !media.audio) { return null; } return external_react_default.a.createElement("button", { type: "button", key: index, "data-title": controlItem.title, className: "control-item media button", onClick: _this3.openBraftFinder }, controlItem.text); } else if (controlItem.type === 'dropdown') { return external_react_default.a.createElement(DropDown_DropDown, extends_default()({ key: index, className: "control-item extend-control-item dropdown ".concat(controlItem.className || ''), caption: controlItem.text, htmlCaption: controlItem.html, showArrow: controlItem.showArrow, title: controlItem.title, arrowActive: controlItem.arrowActive, theme: controlItem.theme, autoHide: controlItem.autoHide, disabled: controlItem.disabled, ref: controlItem.ref }, commonProps), controlItem.component); } else if (controlItem.type === 'modal') { return external_react_default.a.createElement("button", { type: "button", key: index, "data-title": controlItem.title, className: "control-item extend-control-item button ".concat(controlItem.className || ''), dangerouslySetInnerHTML: controlItem.html ? { __html: controlItem.html } : null, onClick: function onClick(event) { if (controlItem.modal && controlItem.modal.id) { if (_this3.extendedModals[controlItem.modal.id]) { _this3.extendedModals[controlItem.modal.id].active = true; _this3.extendedModals[controlItem.modal.id].update(objectSpread_default()({}, controlItem.modal, { language: language })); } else { _this3.extendedModals[controlItem.modal.id] = Modal_showModal(objectSpread_default()({}, controlItem.modal, { language: language })); controlItem.modal.onCreate && controlItem.modal.onCreate(_this3.extendedModals[controlItem.modal.id]); } } controlItem.onClick && controlItem.onClick(event); } }, !controlItem.html ? controlItem.text : null); } else if (controlItem.type === 'component') { return external_react_default.a.createElement("div", { key: index, className: "component-wrapper ".concat(controlItem.className || '') }, controlItem.component); } else if (controlItem.type === 'button') { return external_react_default.a.createElement("button", { type: "button", key: index, "data-title": controlItem.title, className: "control-item button ".concat(controlItem.className || ''), dangerouslySetInnerHTML: controlItem.html ? { __html: controlItem.html } : null, onClick: function onClick(event) { return controlItem.onClick && controlItem.onClick(event); } }, !controlItem.html ? controlItem.text : null); } else if (controlItem) { var disabled = false; if (controlItem.command === 'undo') { disabled = editorState.getUndoStack().size === 0; } else if (controlItem.command === 'redo') { disabled = editorState.getRedoStack().size === 0; } return external_react_default.a.createElement("button", { type: "button", key: index, disabled: disabled, "data-title": controlItem.title, className: _this3.getControlItemClassName({ type: controlItem.type, command: controlItem.command }), onClick: function onClick() { return _this3.applyControl(controlItem.command, controlItem.type, controlItem.data); } }, controlItem.text); } })); } }, { key: "preventDefault", value: function preventDefault(event) { var tagName = event.target.tagName.toLowerCase(); if (tagName === 'input' || tagName === 'label') {// ... } else { event.preventDefault(); } } }]); return ControlBar; }(external_react_default.a.Component); // CONCATENATED MODULE: ./editor/index.jsx var buildHooks = function buildHooks(hooks) { return function (hookName) { var defaultReturns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return hooks[hookName] || function () { return defaultReturns; }; }; }; var filterColors = function filterColors(colors, colors2) { return colors.filter(function (item) { return colors2.indexOf(item) === -1; }).filter(function (item, index, array) { return array.indexOf(item) === index; }); }; var editor_isControlEnabled = function isControlEnabled(props, controlName) { return toConsumableArray_default()(props.controls).concat(toConsumableArray_default()(props.extendControls)).find(function (item) { return item === controlName || item.key === controlName; }) && props.excludeControls.indexOf(controlName) === -1; }; var editor_getConvertOptions = function getConvertOptions(props) { var convertOptions = objectSpread_default()({}, configs_props.converts, props.converts, { fontFamilies: props.fontFamilies }); convertOptions.styleImportFn = compositeStyleImportFn(convertOptions.styleImportFn, props.id); convertOptions.styleExportFn = compositeStyleExportFn(convertOptions.styleExportFn, props.id); convertOptions.entityImportFn = compositeEntityImportFn(convertOptions.entityImportFn, props.id); convertOptions.entityExportFn = compositeEntityExportFn(convertOptions.entityExportFn, props.id); convertOptions.blockImportFn = compositeBlockImportFn(convertOptions.blockImportFn, props.id); convertOptions.blockExportFn = compositeBlockExportFn(convertOptions.blockExportFn, props.id); return convertOptions; }; var editor_BraftEditor = /*#__PURE__*/ function (_React$Component) { inherits_default()(BraftEditor, _React$Component); function BraftEditor(props) { var _this; classCallCheck_default()(this, BraftEditor); _this = possibleConstructorReturn_default()(this, getPrototypeOf_default()(BraftEditor).call(this, props)); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onChange", function (editorState, callback) { if (!(editorState instanceof external_draft_js_["EditorState"])) { editorState = external_draft_js_["EditorState"].set(editorState, { decorator: _this.editorDecorators }); } if (!editorState.convertOptions) { editorState.setConvertOptions(editor_getConvertOptions(_this.editorProps)); } _this.setState({ editorState: editorState }, function () { _this.props.onChange && _this.props.onChange(editorState); callback && callback(editorState); }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "getDraftInstance", function () { return _this.draftInstance; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "getFinderInstance", function () { return _this.braftFinder; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "getValue", function () { return _this.state.editorState; }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setValue", function (editorState, callback) { return _this.onChange(editorState, callback); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "forceRender", function () { return _this.setValue(external_braft_utils_["ContentUtils"].createEditorState(_this.state.editorState.getCurrentContent(), _this.editorDecorators)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onTab", function (event) { if (handlers_keyCommandHandlers('tab', _this.state.editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this))) === 'handled') { event.preventDefault(); } _this.editorProps.onTab && _this.editorProps.onTab(event); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onFocus", function () { _this.isFocused = true; _this.editorProps.onFocus && _this.editorProps.onFocus(_this.state.editorState); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onBlur", function () { _this.isFocused = false; _this.editorProps.onBlur && _this.editorProps.onBlur(_this.state.editorState); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "requestFocus", function () { setTimeout(function () { return _this.draftInstance.focus(); }, 0); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleKeyCommand", function (command, editorState) { return handlers_keyCommandHandlers(command, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleReturn", function (event, editorState) { return handlers_returnHandlers(event, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleBeforeInput", function (chars, editorState) { return beforeInputHandlers(chars, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDrop", function (selectionState, dataTransfer) { return handlers_dropHandlers(selectionState, dataTransfer, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDroppedFiles", function (selectionState, files) { return droppedFilesHandlers(selectionState, files, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handlePastedFiles", function (files) { return pastedFilesHandlers(files, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCopyContent", function (event) { return handlers_copyHandlers(event, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handlePastedText", function (text, html, editorState) { return handlers_pastedTextHandlers(text, html, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCompositionStart", function (event) { return handlers_compositionStartHandler(event, assertThisInitialized_default()(assertThisInitialized_default()(_this))); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "undo", function () { _this.setValue(external_braft_utils_["ContentUtils"].undo(_this.state.editorState)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "redo", function () { _this.setValue(external_braft_utils_["ContentUtils"].redo(_this.state.editorState)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeSelectionInlineStyles", function () { _this.setValue(external_braft_utils_["ContentUtils"].removeSelectionInlineStyles(_this.state.editorState)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "insertHorizontalLine", function () { _this.setValue(external_braft_utils_["ContentUtils"].insertHorizontalLine(_this.state.editorState)); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "clearEditorContent", function () { _this.setValue(external_braft_utils_["ContentUtils"].clear(_this.state.editorState), function (editorState) { _this.setValue(external_braft_utils_["ContentUtils"].toggleSelectionIndent(editorState, 0)); }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleFullscreen", function (fullscreen) { _this.setState({ isFullscreen: typeof fullscreen !== 'undefined' ? fullscreen : !_this.state.isFullscreen }, function () { _this.editorProps.onFullscreen && _this.editorProps.onFullscreen(_this.state.isFullscreen); }); }); defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setEditorContainerNode", function (containerNode) { _this.setState({ containerNode: containerNode }, _this.forceRender); }); _this.editorProps = _this.getEditorProps(props); _this.editorDecorators = getDecorators(_this.editorProps.id); _this.isFocused = false; _this.isLiving = false; _this.braftFinder = null; _this.valueInitialized = !!(_this.props.defaultValue || _this.props.value); var defaultEditorState = (_this.props.defaultValue || _this.props.value) instanceof external_draft_js_["EditorState"] ? _this.props.defaultValue || _this.props.value : external_draft_js_["EditorState"].createEmpty(_this.editorDecorators); defaultEditorState.setConvertOptions(editor_getConvertOptions(_this.editorProps)); _this.state = { containerNode: null, tempColors: [], editorState: defaultEditorState, isFullscreen: false, draftProps: {} }; return _this; } createClass_default()(BraftEditor, [{ key: "getEditorProps", value: function getEditorProps(props) { var _this2 = this; props = props || this.props; var _props = props, value = _props.value, defaultValue = _props.defaultValue, onChange = _props.onChange, restProps = objectWithoutProperties_default()(_props, ["value", "defaultValue", "onChange"]); // eslint-disable-line no-unused-vars var propInterceptors = getPropInterceptors(restProps.id); if (propInterceptors.length === 0) { return restProps; } var porpsMap = Object(external_immutable_["Map"])(restProps); propInterceptors.forEach(function (interceptor) { porpsMap = porpsMap.merge(Object(external_immutable_["Map"])(interceptor(porpsMap.toJS(), _this2) || {})); }); return porpsMap.toJS(); } }, { key: "componentWillMount", value: function componentWillMount() { if (editor_isControlEnabled(this.editorProps, 'media')) { var _this$editorProps = this.editorProps, language = _this$editorProps.language, media = _this$editorProps.media; var _defaultProps$media$m = objectSpread_default()({}, configs_props.media, media), uploadFn = _defaultProps$media$m.uploadFn, validateFn = _defaultProps$media$m.validateFn, items = _defaultProps$media$m.items; this.braftFinder = new external_braft_finder_default.a({ items: items, language: language, uploader: uploadFn, validator: validateFn }); this.forceUpdate(); } } }, { key: "componentDidMount", value: function componentDidMount() { var _this3 = this; this.editorProps = this.getEditorProps(); var editorState = this.props.value; if (external_braft_utils_["ContentUtils"].isEditorState(editorState)) { var tempColors = external_braft_utils_["ColorUtils"].detectColorsFromDraftState(editorState.toRAW(true)); editorState.setConvertOptions(editor_getConvertOptions(this.editorProps)); this.setState({ tempColors: filterColors(toConsumableArray_default()(this.state.tempColors).concat(toConsumableArray_default()(tempColors)), this.editorProps.colors), editorState: editorState }, function () { _this3.props.triggerChangeOnMount && _this3.props.onChange && _this3.props.onChange(editorState); }); } this.isLiving = true; } }, { key: "componentDidUpdate", value: function componentDidUpdate(_, prevState) { if (prevState.editorState !== this.state.editorState) { this.state.editorState.setConvertOptions(editor_getConvertOptions(this.editorProps)); } } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(props) { var _this4 = this; this.editorProps = this.getEditorProps(props); var editorState = props.value; var _this$editorProps2 = this.editorProps, media = _this$editorProps2.media, language = _this$editorProps2.language; var currentProps = this.getEditorProps(); if (!editor_isControlEnabled(currentProps, 'media') && editor_isControlEnabled(this.editorProps, 'media') && !this.braftFinder) { var _defaultProps$media$m2 = objectSpread_default()({}, configs_props.media, media), uploadFn = _defaultProps$media$m2.uploadFn, validateFn = _defaultProps$media$m2.validateFn, items = _defaultProps$media$m2.items; this.braftFinder = new external_braft_finder_default.a({ items: items, language: language, uploader: uploadFn, validator: validateFn }); this.forceUpdate(); } if (media && media.items && this.braftFinder) { this.braftFinder.setItems(media.items); } var nextEditorState; if (!this.valueInitialized && typeof this.props.defaultValue === 'undefined' && external_braft_utils_["ContentUtils"].isEditorState(props.defaultValue)) { nextEditorState = props.defaultValue; } else if (external_braft_utils_["ContentUtils"].isEditorState(editorState)) { nextEditorState = editorState; } if (nextEditorState) { if (nextEditorState && nextEditorState !== this.state.editorState) { var tempColors = external_braft_utils_["ColorUtils"].detectColorsFromDraftState(nextEditorState.toRAW(true)); nextEditorState.setConvertOptions(editor_getConvertOptions(this.editorProps)); this.setState({ tempColors: filterColors(toConsumableArray_default()(this.state.tempColors).concat(toConsumableArray_default()(tempColors)), currentProps.colors), editorState: nextEditorState }, function () { _this4.props.onChange && _this4.props.onChange(nextEditorState); }); } else { this.setState({ editorState: nextEditorState }); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isLiving = false; this.controlBarInstance && this.controlBarInstance.closeBraftFinder(); } }, { key: "lockOrUnlockEditor", value: function lockOrUnlockEditor(editorLocked) { this.setState({ editorLocked: editorLocked }); } }, { key: "render", value: function render() { var _this5 = this; var _this$editorProps3 = this.editorProps, editorId = _this$editorProps3.id, controls = _this$editorProps3.controls, excludeControls = _this$editorProps3.excludeControls, extendControls = _this$editorProps3.extendControls, readOnly = _this$editorProps3.readOnly, disabled = _this$editorProps3.disabled, media = _this$editorProps3.media, language = _this$editorProps3.language, colors = _this$editorProps3.colors, colorPicker = _this$editorProps3.colorPicker, colorPickerTheme = _this$editorProps3.colorPickerTheme, colorPickerAutoHide = _this$editorProps3.colorPickerAutoHide, hooks = _this$editorProps3.hooks, fontSizes = _this$editorProps3.fontSizes, fontFamilies = _this$editorProps3.fontFamilies, emojis = _this$editorProps3.emojis, placeholder = _this$editorProps3.placeholder, imageControls = _this$editorProps3.imageControls, lineHeights = _this$editorProps3.lineHeights, letterSpacings = _this$editorProps3.letterSpacings, textAligns = _this$editorProps3.textAligns, textBackgroundColor = _this$editorProps3.textBackgroundColor, defaultLinkTarget = _this$editorProps3.defaultLinkTarget, extendAtomics = _this$editorProps3.extendAtomics, className = _this$editorProps3.className, style = _this$editorProps3.style, controlBarClassName = _this$editorProps3.controlBarClassName, controlBarStyle = _this$editorProps3.controlBarStyle, contentClassName = _this$editorProps3.contentClassName, contentStyle = _this$editorProps3.contentStyle, stripPastedStyles = _this$editorProps3.stripPastedStyles, componentBelowControlBar = _this$editorProps3.componentBelowControlBar; var isFullscreen = this.state.isFullscreen; hooks = buildHooks(hooks); controls = controls.filter(function (item) { return excludeControls.indexOf(item) === -1; }); language = (typeof language === 'function' ? language(languages, 'braft-editor') : languages[language]) || languages[configs_props.language]; var externalMedias = media && media.externals ? objectSpread_default()({}, configs_props.media.externals, media.externals) : configs_props.media.externals; var accepts = media && media.accepts ? objectSpread_default()({}, configs_props.media.accepts, media.accepts) : configs_props.media.accepts; media = objectSpread_default()({}, configs_props.media, media, { externalMedias: externalMedias, accepts: accepts }); if (!media.uploadFn) { media.video = false; media.audio = false; } var controlBarProps = { editor: this, editorState: this.state.editorState, braftFinder: this.braftFinder, ref: function ref(instance) { return _this5.controlBarInstance = instance; }, containerNode: this.state.containerNode, className: controlBarClassName, style: controlBarStyle, colors: toConsumableArray_default()(colors).concat(toConsumableArray_default()(this.state.tempColors)), colorPicker: colorPicker, colorPickerTheme: colorPickerTheme, colorPickerAutoHide: colorPickerAutoHide, hooks: hooks, editorId: editorId, media: media, controls: controls, language: language, extendControls: extendControls, fontSizes: fontSizes, fontFamilies: fontFamilies, emojis: emojis, lineHeights: lineHeights, letterSpacings: letterSpacings, textAligns: textAligns, textBackgroundColor: textBackgroundColor, defaultLinkTarget: defaultLinkTarget }; var unitExportFn = this.state.editorState.convertOptions.unitExportFn; var commonProps = { editor: this, editorId: editorId, hooks: hooks, editorState: this.state.editorState, containerNode: this.state.containerNode, imageControls: imageControls, language: language, extendAtomics: extendAtomics }; var blockRendererFn = getBlockRendererFn(commonProps, this.editorProps.blockRendererFn); var blockRenderMap = getBlockRenderMap(commonProps, this.editorProps.blockRenderMap); var blockStyleFn = getBlockStyleFn(this.editorProps.blockStyleFn); var customStyleMap = getCustomStyleMap(commonProps, this.editorProps.customStyleMap); var customStyleFn = getCustomStyleFn(commonProps, { fontFamilies: fontFamilies, unitExportFn: unitExportFn, customStyleFn: this.editorProps.customStyleFn }); var keyBindingFn = keybindings(this.editorProps.keyBindingFn); var mixedProps = {}; if (this.state.editorLocked || this.editorProps.disabled || this.editorProps.readOnly || this.editorProps.draftProps.readOnly) { mixedProps.readOnly = true; } var draftProps = objectSpread_default()({ ref: function ref(instance) { _this5.draftInstance = instance; }, editorState: this.state.editorState, handleKeyCommand: this.handleKeyCommand, handleReturn: this.handleReturn, handleBeforeInput: this.handleBeforeInput, handleDrop: this.handleDrop, handleDroppedFiles: this.handleDroppedFiles, handlePastedText: this.handlePastedText, handlePastedFiles: this.handlePastedFiles, onChange: this.onChange, onTab: this.onTab, onFocus: this.onFocus, onBlur: this.onBlur, blockRenderMap: blockRenderMap, blockRendererFn: blockRendererFn, blockStyleFn: blockStyleFn, customStyleMap: customStyleMap, customStyleFn: customStyleFn, keyBindingFn: keyBindingFn, placeholder: placeholder, stripPastedStyles: stripPastedStyles }, this.editorProps.draftProps, mixedProps); return external_react_default.a.createElement("div", { style: style, ref: this.setEditorContainerNode, className: "bf-container ".concat(className).concat(disabled ? ' disabled' : '').concat(readOnly ? ' read-only' : '').concat(isFullscreen ? ' fullscreen' : ''), onCopy: this.handleCopyContent }, external_react_default.a.createElement(ControlBar_ControlBar, controlBarProps), componentBelowControlBar, external_react_default.a.createElement("div", { onCompositionStart: this.handleCompositionStart, className: "bf-content ".concat(contentClassName), style: contentStyle }, external_react_default.a.createElement(external_draft_js_["Editor"], draftProps))); } }]); return BraftEditor; }(external_react_default.a.Component); defineProperty_default()(editor_BraftEditor, "defaultProps", configs_props); // EXTERNAL MODULE: external "braft-convert" var external_braft_convert_ = __webpack_require__(14); // CONCATENATED MODULE: ./index.jsx /* concated harmony reexport EditorState */__webpack_require__.d(__webpack_exports__, "EditorState", function() { return external_draft_js_["EditorState"]; }); /* concated harmony reexport getDecorators */__webpack_require__.d(__webpack_exports__, "getDecorators", function() { return getDecorators; }); external_draft_js_["EditorState"].prototype.setConvertOptions = function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.convertOptions = options; }; external_draft_js_["EditorState"].prototype.toHTML = function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var convertOptions = this.convertOptions || {}; return Object(external_braft_convert_["convertEditorStateToHTML"])(this, objectSpread_default()({}, convertOptions, options)); }; external_draft_js_["EditorState"].prototype.toRAW = function (noStringify) { return noStringify ? Object(external_braft_convert_["convertEditorStateToRaw"])(this) : JSON.stringify(Object(external_braft_convert_["convertEditorStateToRaw"])(this)); }; external_draft_js_["EditorState"].prototype.toText = function () { return this.getCurrentContent().getPlainText(); }; external_draft_js_["EditorState"].prototype.isEmpty = function () { return !this.getCurrentContent().hasText(); }; editor_BraftEditor.createEditorState = external_draft_js_["EditorState"].createFrom = function (content) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options.unitExportFn = options.unitExportFn || editor_BraftEditor.defaultProps.converts.unitExportFn; options.styleImportFn = compositeStyleImportFn(options.styleImportFn, options.editorId); options.entityImportFn = compositeEntityImportFn(options.entityImportFn, options.editorId); options.blockImportFn = compositeBlockImportFn(options.blockImportFn, options.editorId); var editorState = null; if (content instanceof external_draft_js_["EditorState"]) { editorState = content; } else if (typeof_default()(content) === 'object' && content && content.blocks && content.entityMap) { editorState = Object(external_braft_convert_["convertRawToEditorState"])(content, getDecorators(options.editorId)); } else if (typeof content === 'string') { try { editorState = external_draft_js_["EditorState"].createFrom(JSON.parse(content), options); } catch (error) { editorState = Object(external_braft_convert_["convertHTMLToEditorState"])(content, getDecorators(options.editorId), options, 'create'); } } else { editorState = external_draft_js_["EditorState"].createEmpty(getDecorators(options.editorId)); } options.styleExportFn = compositeStyleExportFn(options.styleExportFn, options.editorId); options.entityExportFn = compositeEntityExportFn(options.entityExportFn, options.editorId); options.blockExportFn = compositeBlockExportFn(options.blockExportFn, options.editorId); editorState.setConvertOptions(options); return editorState; }; /* harmony default export */ var index_0 = __webpack_exports__["default"] = (createExtensibleEditor(editor_BraftEditor)); // 2.1版本开发计划 // [ ]优化选中多行文字是插入链接报错的问题 // [ ]新增编辑器内图片删除hook // 2.2版本开发计划 // [ ]表格功能 // [ ]美化UI,包括图标和界面风格 // 2.3版本开发计划 // [ ]初级md快捷输入支持 // [ ]图片裁切等简单的编辑功能 // [ ]允许自定义快捷键 /***/ }), /* 40 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 41 */, /* 42 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 43 */, /* 44 */, /* 45 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 46 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 47 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 48 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 49 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 50 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 51 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 52 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 53 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 54 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 55 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 56 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 57 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 58 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 59 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 60 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 61 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /* 62 */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }) /******/ ]); }); //# sourceMappingURL=index.js.map /***/ }), /* 943 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorUtils = exports.BaseUtils = exports.ContentUtils = undefined; var _content = __webpack_require__(944); var _ContentUtils = _interopRequireWildcard(_content); var _base = __webpack_require__(1049); var _BaseUtils = _interopRequireWildcard(_base); var _color = __webpack_require__(1050); var _ColorUtils = _interopRequireWildcard(_color); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var ContentUtils = exports.ContentUtils = _ContentUtils; var BaseUtils = exports.BaseUtils = _BaseUtils; var ColorUtils = exports.ColorUtils = _ColorUtils; /***/ }), /* 944 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.redo = exports.undo = exports.handleKeyCommand = exports.clear = exports.setMediaPosition = exports.removeMedia = exports.setMediaData = exports.insertMedias = exports.insertHorizontalLine = exports.insertAtomicBlock = exports.insertHTML = exports.insertText = exports.toggleSelectionLetterSpacing = exports.toggleSelectionFontFamily = exports.toggleSelectionLineHeight = exports.toggleSelectionFontSize = exports.toggleSelectionBackgroundColor = exports.toggleSelectionColor = exports.decreaseSelectionIndent = exports.increaseSelectionIndent = exports.toggleSelectionIndent = exports.toggleSelectionAlignment = exports.removeSelectionInlineStyles = exports.toggleSelectionInlineStyle = exports.selectionHasInlineStyle = exports.getSelectionInlineStyle = exports.toggleSelectionLink = exports.toggleSelectionEntity = exports.getSelectionEntityData = exports.getSelectionEntityType = exports.toggleSelectionBlockType = exports.getSelectionText = exports.getSelectionBlockType = exports.getSelectionBlockData = exports.setSelectionBlockData = exports.getSelectedBlocks = exports.getSelectionBlock = exports.removeBlock = exports.selectNextBlock = exports.selectBlock = exports.selectionContainsStrictBlock = exports.selectionContainsBlockType = exports.isSelectionCollapsed = exports.createEditorState = exports.createEmptyEditorState = exports.isEditorState = exports.registerStrictBlockType = undefined; var _draftJs = __webpack_require__(83); var _draftjsUtils = __webpack_require__(464); var _braftConvert = __webpack_require__(465); var strictBlockTypes = ['atomic']; var registerStrictBlockType = exports.registerStrictBlockType = function registerStrictBlockType(blockType) { strictBlockTypes.indexOf(blockType) === -1 && strictBlockTypes.push(blockType); }; var isEditorState = exports.isEditorState = function isEditorState(editorState) { return editorState instanceof _draftJs.EditorState; }; var createEmptyEditorState = exports.createEmptyEditorState = function createEmptyEditorState(editorDecorators) { return _draftJs.EditorState.createEmpty(editorDecorators); }; var createEditorState = exports.createEditorState = function createEditorState(contentState, editorDecorators) { return _draftJs.EditorState.createWithContent(contentState, editorDecorators); }; var isSelectionCollapsed = exports.isSelectionCollapsed = function isSelectionCollapsed(editorState) { return editorState.getSelection().isCollapsed(); }; var selectionContainsBlockType = exports.selectionContainsBlockType = function selectionContainsBlockType(editorState, blockType) { return getSelectedBlocks(editorState).find(function (block) { return block.getType() === blockType; }); }; var selectionContainsStrictBlock = exports.selectionContainsStrictBlock = function selectionContainsStrictBlock(editorState) { return getSelectedBlocks(editorState).find(function (block) { return ~strictBlockTypes.indexOf(block.getType()); }); }; var selectBlock = exports.selectBlock = function selectBlock(editorState, block) { var blockKey = block.getKey(); return _draftJs.EditorState.forceSelection(editorState, new _draftJs.SelectionState({ anchorKey: blockKey, anchorOffset: 0, focusKey: blockKey, focusOffset: block.getLength() })); }; var selectNextBlock = exports.selectNextBlock = function selectNextBlock(editorState, block) { var nextBlock = editorState.getCurrentContent().getBlockAfter(block.getKey()); return nextBlock ? selectBlock(editorState, nextBlock) : editorState; }; var removeBlock = exports.removeBlock = function removeBlock(editorState, block) { var lastSelection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var nextContentState = void 0, nextEditorState = void 0; var blockKey = block.getKey(); nextContentState = _draftJs.Modifier.removeRange(editorState.getCurrentContent(), new _draftJs.SelectionState({ anchorKey: blockKey, anchorOffset: 0, focusKey: blockKey, focusOffset: block.getLength() }), 'backward'); nextContentState = _draftJs.Modifier.setBlockType(nextContentState, nextContentState.getSelectionAfter(), 'unstyled'); nextEditorState = _draftJs.EditorState.push(editorState, nextContentState, 'remove-range'); return _draftJs.EditorState.forceSelection(nextEditorState, lastSelection || nextContentState.getSelectionAfter()); }; var getSelectionBlock = exports.getSelectionBlock = function getSelectionBlock(editorState) { return editorState.getCurrentContent().getBlockForKey(editorState.getSelection().getAnchorKey()); }; var getSelectedBlocks = exports.getSelectedBlocks = function getSelectedBlocks(editorState) { var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); var startKey = selectionState.getStartKey(); var endKey = selectionState.getEndKey(); var isSameBlock = startKey === endKey; var startingBlock = contentState.getBlockForKey(startKey); var selectedBlocks = [startingBlock]; if (!isSameBlock) { var blockKey = startKey; while (blockKey !== endKey) { var nextBlock = contentState.getBlockAfter(blockKey); selectedBlocks.push(nextBlock); blockKey = nextBlock.getKey(); } } return selectedBlocks; }; var setSelectionBlockData = exports.setSelectionBlockData = function setSelectionBlockData(editorState, blockData, override) { var newBlockData = override ? blockData : Object.assign({}, getSelectionBlockData(editorState).toJS(), blockData); Object.keys(newBlockData).forEach(function (key) { if (newBlockData.hasOwnProperty(key) && newBlockData[key] === undefined) { delete newBlockData[key]; } }); return (0, _draftjsUtils.setBlockData)(editorState, newBlockData); }; var getSelectionBlockData = exports.getSelectionBlockData = function getSelectionBlockData(editorState, name) { var blockData = getSelectionBlock(editorState).getData(); return name ? blockData.get(name) : blockData; }; var getSelectionBlockType = exports.getSelectionBlockType = function getSelectionBlockType(editorState) { return getSelectionBlock(editorState).getType(); }; var getSelectionText = exports.getSelectionText = function getSelectionText(editorState) { var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return ''; } var anchorKey = selectionState.getAnchorKey(); var currentContentBlock = contentState.getBlockForKey(anchorKey); var start = selectionState.getStartOffset(); var end = selectionState.getEndOffset(); return currentContentBlock.getText().slice(start, end); }; var toggleSelectionBlockType = exports.toggleSelectionBlockType = function toggleSelectionBlockType(editorState, blockType) { if (selectionContainsStrictBlock(editorState)) { return editorState; } return _draftJs.RichUtils.toggleBlockType(editorState, blockType); }; var getSelectionEntityType = exports.getSelectionEntityType = function getSelectionEntityType(editorState) { var entityKey = (0, _draftjsUtils.getSelectionEntity)(editorState); if (entityKey) { var entity = editorState.getCurrentContent().getEntity(entityKey); return entity ? entity.get('type') : null; } return null; }; var getSelectionEntityData = exports.getSelectionEntityData = function getSelectionEntityData(editorState, type) { var entityKey = (0, _draftjsUtils.getSelectionEntity)(editorState); if (entityKey) { var entity = editorState.getCurrentContent().getEntity(entityKey); if (entity && entity.get('type') === type) { return entity.getData(); } else { return {}; } } else { return {}; } }; var toggleSelectionEntity = exports.toggleSelectionEntity = function toggleSelectionEntity(editorState, entity) { var contentState = editorState.getCurrentContent(); var selectionState = editorState.getSelection(); if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return editorState; } if (!entity || !entity.type || getSelectionEntityType(editorState) === entity.type) { return _draftJs.EditorState.push(editorState, _draftJs.Modifier.applyEntity(contentState, selectionState, null), 'apply-entity'); } try { var nextContentState = contentState.createEntity(entity.type, entity.mutability, entity.data); var entityKey = nextContentState.getLastCreatedEntityKey(); var nextEditorState = _draftJs.EditorState.set(editorState, { currentContent: nextContentState }); return _draftJs.EditorState.push(nextEditorState, _draftJs.Modifier.applyEntity(nextContentState, selectionState, entityKey), 'apply-entity'); } catch (error) { console.warn(error); return editorState; } }; var toggleSelectionLink = exports.toggleSelectionLink = function toggleSelectionLink(editorState, href, target) { var contentState = editorState.getCurrentContent(); var selectionState = editorState.getSelection(); var entityData = { href: href, target: target }; if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return editorState; } if (href === false) { return _draftJs.RichUtils.toggleLink(editorState, selectionState, null); } if (href === null) { delete entityData.href; } try { var nextContentState = contentState.createEntity('LINK', 'MUTABLE', entityData); var entityKey = nextContentState.getLastCreatedEntityKey(); var nextEditorState = _draftJs.EditorState.set(editorState, { currentContent: nextContentState }); nextEditorState = _draftJs.RichUtils.toggleLink(nextEditorState, selectionState, entityKey); nextEditorState = _draftJs.EditorState.forceSelection(nextEditorState, selectionState.merge({ anchorOffset: selectionState.getEndOffset(), focusOffset: selectionState.getEndOffset() })); nextEditorState = _draftJs.EditorState.push(nextEditorState, _draftJs.Modifier.insertText(nextEditorState.getCurrentContent(), nextEditorState.getSelection(), ' '), 'insert-text'); return nextEditorState; } catch (error) { console.warn(error); return editorState; } }; var getSelectionInlineStyle = exports.getSelectionInlineStyle = function getSelectionInlineStyle(editorState) { return editorState.getCurrentInlineStyle(); }; var selectionHasInlineStyle = exports.selectionHasInlineStyle = function selectionHasInlineStyle(editorState, style) { return getSelectionInlineStyle(editorState).has(style.toUpperCase()); }; var toggleSelectionInlineStyle = exports.toggleSelectionInlineStyle = function toggleSelectionInlineStyle(editorState, style) { var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; style = prefix + style.toUpperCase(); var stylesToBeRemoved = prefix ? editorState.getCurrentInlineStyle().toJS().filter(function (item) { return item.indexOf(prefix) === 0 && item !== style; }) : []; var nextEditorState = stylesToBeRemoved.length ? stylesToBeRemoved.reduce(function (editorState, item) { return _draftJs.RichUtils.toggleInlineStyle(editorState, item); }, editorState) : editorState; return _draftJs.RichUtils.toggleInlineStyle(nextEditorState, style); }; var removeSelectionInlineStyles = exports.removeSelectionInlineStyles = function removeSelectionInlineStyles(editorState) { return (0, _draftjsUtils.removeAllInlineStyles)(editorState); }; var toggleSelectionAlignment = exports.toggleSelectionAlignment = function toggleSelectionAlignment(editorState, alignment) { return setSelectionBlockData(editorState, { textAlign: getSelectionBlockData(editorState, 'textAlign') !== alignment ? alignment : undefined }); }; var toggleSelectionIndent = exports.toggleSelectionIndent = function toggleSelectionIndent(editorState, textIndent) { var maxIndent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 6; return textIndent < 0 || textIndent > maxIndent || isNaN(textIndent) ? editorState : setSelectionBlockData(editorState, { textIndent: textIndent || undefined }); }; var increaseSelectionIndent = exports.increaseSelectionIndent = function increaseSelectionIndent(editorState) { var maxIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6; var currentIndent = getSelectionBlockData(editorState, 'textIndent') || 0; return toggleSelectionIndent(editorState, currentIndent + 1, maxIndent); }; var decreaseSelectionIndent = exports.decreaseSelectionIndent = function decreaseSelectionIndent(editorState) { var currentIndent = getSelectionBlockData(editorState, 'textIndent') || 0; return toggleSelectionIndent(editorState, currentIndent - 1); }; var toggleSelectionColor = exports.toggleSelectionColor = function toggleSelectionColor(editorState, color) { return toggleSelectionInlineStyle(editorState, color.replace('#', ''), 'COLOR-'); }; var toggleSelectionBackgroundColor = exports.toggleSelectionBackgroundColor = function toggleSelectionBackgroundColor(editorState, color) { return toggleSelectionInlineStyle(editorState, color.replace('#', ''), 'BGCOLOR-'); }; var toggleSelectionFontSize = exports.toggleSelectionFontSize = function toggleSelectionFontSize(editorState, fontSize) { return toggleSelectionInlineStyle(editorState, fontSize, 'FONTSIZE-'); }; var toggleSelectionLineHeight = exports.toggleSelectionLineHeight = function toggleSelectionLineHeight(editorState, lineHeight) { return toggleSelectionInlineStyle(editorState, lineHeight, 'LINEHEIGHT-'); }; var toggleSelectionFontFamily = exports.toggleSelectionFontFamily = function toggleSelectionFontFamily(editorState, fontFamily) { return toggleSelectionInlineStyle(editorState, fontFamily, 'FONTFAMILY-'); }; var toggleSelectionLetterSpacing = exports.toggleSelectionLetterSpacing = function toggleSelectionLetterSpacing(editorState, letterSpacing) { return toggleSelectionInlineStyle(editorState, letterSpacing, 'LETTERSPACING-'); }; var insertText = exports.insertText = function insertText(editorState, text, inlineStyle, entity) { var selectionState = editorState.getSelection(); var currentSelectedBlockType = getSelectionBlockType(editorState); if (currentSelectedBlockType === 'atomic') { return editorState; } var entityKey = void 0; var contentState = editorState.getCurrentContent(); if (entity && entity.type) { contentState = contentState.createEntity(entity.type, entity.mutability || 'MUTABLE', entity.data || entityData); entityKey = contentState.getLastCreatedEntityKey(); } if (!selectionState.isCollapsed()) { return _draftJs.EditorState.push(editorState, _draftJs.Modifier.replaceText(contentState, selectionState, text, inlineStyle, entityKey), 'replace-text'); } else { return _draftJs.EditorState.push(editorState, _draftJs.Modifier.insertText(contentState, selectionState, text, inlineStyle, entityKey), 'insert-text'); } }; var insertHTML = exports.insertHTML = function insertHTML(editorState, htmlString, source) { if (!htmlString) { return editorState; } var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); var options = editorState.convertOptions || {}; try { var _convertFromRaw = (0, _draftJs.convertFromRaw)((0, _braftConvert.convertHTMLToRaw)(htmlString, options, source)), blockMap = _convertFromRaw.blockMap; return _draftJs.EditorState.push(editorState, _draftJs.Modifier.replaceWithFragment(contentState, selectionState, blockMap), 'insert-fragment'); } catch (error) { console.warn(error); return editorState; } }; var insertAtomicBlock = exports.insertAtomicBlock = function insertAtomicBlock(editorState, type) { var immutable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (selectionContainsStrictBlock(editorState)) { return insertAtomicBlock(selectNextBlock(editorState, getSelectionBlock(editorState)), type, immutable, data); } var selectionState = editorState.getSelection(); var contentState = editorState.getCurrentContent(); if (!selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') { return editorState; } var contentStateWithEntity = contentState.createEntity(type, immutable ? 'IMMUTABLE' : 'MUTABLE', data); var entityKey = contentStateWithEntity.getLastCreatedEntityKey(); var newEditorState = _draftJs.AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' '); return newEditorState; }; var insertHorizontalLine = exports.insertHorizontalLine = function insertHorizontalLine(editorState) { return insertAtomicBlock(editorState, 'HR'); }; var insertMedias = exports.insertMedias = function insertMedias(editorState) { var medias = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (!medias.length) { return editorState; } return medias.reduce(function (editorState, media) { var url = media.url, link = media.link, link_target = media.link_target, name = media.name, type = media.type, width = media.width, height = media.height, meta = media.meta; return insertAtomicBlock(editorState, type, true, { url: url, link: link, link_target: link_target, name: name, type: type, width: width, height: height, meta: meta }); }, editorState); }; var setMediaData = exports.setMediaData = function setMediaData(editorState, entityKey, data) { return _draftJs.EditorState.push(editorState, editorState.getCurrentContent().mergeEntityData(entityKey, data), 'change-block-data'); }; var removeMedia = exports.removeMedia = function removeMedia(editorState, mediaBlock) { return removeBlock(editorState, mediaBlock); }; var setMediaPosition = exports.setMediaPosition = function setMediaPosition(editorState, mediaBlock, position) { var newPosition = {}; var float = position.float, alignment = position.alignment; if (typeof float !== 'undefined') { newPosition.float = mediaBlock.getData().get('float') === float ? null : float; } if (typeof alignment !== 'undefined') { newPosition.alignment = mediaBlock.getData().get('alignment') === alignment ? null : alignment; } return setSelectionBlockData(selectBlock(editorState, mediaBlock), newPosition); }; var clear = exports.clear = function clear(editorState) { var contentState = editorState.getCurrentContent(); var firstBlock = contentState.getFirstBlock(); var lastBlock = contentState.getLastBlock(); var allSelected = new _draftJs.SelectionState({ anchorKey: firstBlock.getKey(), anchorOffset: 0, focusKey: lastBlock.getKey(), focusOffset: lastBlock.getLength(), hasFocus: true }); return _draftJs.RichUtils.toggleBlockType(_draftJs.EditorState.push(editorState, _draftJs.Modifier.removeRange(contentState, allSelected, 'backward'), 'remove-range'), 'unstyled'); }; var handleKeyCommand = exports.handleKeyCommand = function handleKeyCommand(editorState, command) { return _draftJs.RichUtils.handleKeyCommand(editorState, command); }; var undo = exports.undo = function undo(editorState) { return _draftJs.EditorState.undo(editorState); }; var redo = exports.redo = function redo(editorState) { return _draftJs.EditorState.redo(editorState); }; /***/ }), /* 945 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AtomicBlockUtils * @format * */ var _assign = __webpack_require__(18); var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var BlockMapBuilder = __webpack_require__(102); var CharacterMetadata = __webpack_require__(27); var ContentBlock = __webpack_require__(69); var ContentBlockNode = __webpack_require__(31); var DraftFeatureFlags = __webpack_require__(56); var DraftModifier = __webpack_require__(23); var EditorState = __webpack_require__(15); var Immutable = __webpack_require__(9); var SelectionState = __webpack_require__(84); var generateRandomKey = __webpack_require__(50); var moveBlockInContentState = __webpack_require__(960); var experimentalTreeDataSupport = DraftFeatureFlags.draft_tree_data_support; var ContentBlockRecord = experimentalTreeDataSupport ? ContentBlockNode : ContentBlock; var List = Immutable.List, Repeat = Immutable.Repeat; var AtomicBlockUtils = { insertAtomicBlock: function insertAtomicBlock(editorState, entityKey, character) { var contentState = editorState.getCurrentContent(); var selectionState = editorState.getSelection(); var afterRemoval = DraftModifier.removeRange(contentState, selectionState, 'backward'); var targetSelection = afterRemoval.getSelectionAfter(); var afterSplit = DraftModifier.splitBlock(afterRemoval, targetSelection); var insertionTarget = afterSplit.getSelectionAfter(); var asAtomicBlock = DraftModifier.setBlockType(afterSplit, insertionTarget, 'atomic'); var charData = CharacterMetadata.create({ entity: entityKey }); var atomicBlockConfig = { key: generateRandomKey(), type: 'atomic', text: character, characterList: List(Repeat(charData, character.length)) }; var atomicDividerBlockConfig = { key: generateRandomKey(), type: 'unstyled' }; if (experimentalTreeDataSupport) { atomicBlockConfig = _extends({}, atomicBlockConfig, { nextSibling: atomicDividerBlockConfig.key }); atomicDividerBlockConfig = _extends({}, atomicDividerBlockConfig, { prevSibling: atomicBlockConfig.key }); } var fragmentArray = [new ContentBlockRecord(atomicBlockConfig), new ContentBlockRecord(atomicDividerBlockConfig)]; var fragment = BlockMapBuilder.createFromArray(fragmentArray); var withAtomicBlock = DraftModifier.replaceWithFragment(asAtomicBlock, insertionTarget, fragment); var newContent = withAtomicBlock.merge({ selectionBefore: selectionState, selectionAfter: withAtomicBlock.getSelectionAfter().set('hasFocus', true) }); return EditorState.push(editorState, newContent, 'insert-fragment'); }, moveAtomicBlock: function moveAtomicBlock(editorState, atomicBlock, targetRange, insertionMode) { var contentState = editorState.getCurrentContent(); var selectionState = editorState.getSelection(); var withMovedAtomicBlock = void 0; if (insertionMode === 'before' || insertionMode === 'after') { var targetBlock = contentState.getBlockForKey(insertionMode === 'before' ? targetRange.getStartKey() : targetRange.getEndKey()); withMovedAtomicBlock = moveBlockInContentState(contentState, atomicBlock, targetBlock, insertionMode); } else { var afterRemoval = DraftModifier.removeRange(contentState, targetRange, 'backward'); var selectionAfterRemoval = afterRemoval.getSelectionAfter(); var _targetBlock = afterRemoval.getBlockForKey(selectionAfterRemoval.getFocusKey()); if (selectionAfterRemoval.getStartOffset() === 0) { withMovedAtomicBlock = moveBlockInContentState(afterRemoval, atomicBlock, _targetBlock, 'before'); } else if (selectionAfterRemoval.getEndOffset() === _targetBlock.getLength()) { withMovedAtomicBlock = moveBlockInContentState(afterRemoval, atomicBlock, _targetBlock, 'after'); } else { var afterSplit = DraftModifier.splitBlock(afterRemoval, selectionAfterRemoval); var selectionAfterSplit = afterSplit.getSelectionAfter(); var _targetBlock2 = afterSplit.getBlockForKey(selectionAfterSplit.getFocusKey()); withMovedAtomicBlock = moveBlockInContentState(afterSplit, atomicBlock, _targetBlock2, 'before'); } } var newContent = withMovedAtomicBlock.merge({ selectionBefore: selectionState, selectionAfter: withMovedAtomicBlock.getSelectionAfter().set('hasFocus', true) }); return EditorState.push(editorState, newContent, 'move-block'); } }; module.exports = AtomicBlockUtils; /***/ }), /* 946 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftFeatureFlags-core * @format * */ var DraftFeatureFlags = { draft_killswitch_allow_nontextnodes: false, draft_segmented_entities_behavior: false, draft_handlebeforeinput_composed_text: false, draft_tree_data_support: false }; module.exports = DraftFeatureFlags; /***/ }), /* 947 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ContentStateInlineStyle * @format * */ var CharacterMetadata = __webpack_require__(27); var _require = __webpack_require__(9), Map = _require.Map; var ContentStateInlineStyle = { add: function add(contentState, selectionState, inlineStyle) { return modifyInlineStyle(contentState, selectionState, inlineStyle, true); }, remove: function remove(contentState, selectionState, inlineStyle) { return modifyInlineStyle(contentState, selectionState, inlineStyle, false); } }; function modifyInlineStyle(contentState, selectionState, inlineStyle, addOrRemove) { var blockMap = contentState.getBlockMap(); var startKey = selectionState.getStartKey(); var startOffset = selectionState.getStartOffset(); var endKey = selectionState.getEndKey(); var endOffset = selectionState.getEndOffset(); var newBlocks = blockMap.skipUntil(function (_, k) { return k === startKey; }).takeUntil(function (_, k) { return k === endKey; }).concat(Map([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) { var sliceStart; var sliceEnd; if (startKey === endKey) { sliceStart = startOffset; sliceEnd = endOffset; } else { sliceStart = blockKey === startKey ? startOffset : 0; sliceEnd = blockKey === endKey ? endOffset : block.getLength(); } var chars = block.getCharacterList(); var current; while (sliceStart < sliceEnd) { current = chars.get(sliceStart); chars = chars.set(sliceStart, addOrRemove ? CharacterMetadata.applyStyle(current, inlineStyle) : CharacterMetadata.removeStyle(current, inlineStyle)); sliceStart++; } return block.set('characterList', chars); }); return contentState.merge({ blockMap: blockMap.merge(newBlocks), selectionBefore: selectionState, selectionAfter: selectionState }); } module.exports = ContentStateInlineStyle; /***/ }), /* 948 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule applyEntityToContentState * @format * */ var Immutable = __webpack_require__(9); var applyEntityToContentBlock = __webpack_require__(949); function applyEntityToContentState(contentState, selectionState, entityKey) { var blockMap = contentState.getBlockMap(); var startKey = selectionState.getStartKey(); var startOffset = selectionState.getStartOffset(); var endKey = selectionState.getEndKey(); var endOffset = selectionState.getEndOffset(); var newBlocks = blockMap.skipUntil(function (_, k) { return k === startKey; }).takeUntil(function (_, k) { return k === endKey; }).toOrderedMap().merge(Immutable.OrderedMap([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) { var sliceStart = blockKey === startKey ? startOffset : 0; var sliceEnd = blockKey === endKey ? endOffset : block.getLength(); return applyEntityToContentBlock(block, sliceStart, sliceEnd, entityKey); }); return contentState.merge({ blockMap: blockMap.merge(newBlocks), selectionBefore: selectionState, selectionAfter: selectionState }); } module.exports = applyEntityToContentState; /***/ }), /* 949 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule applyEntityToContentBlock * @format * */ var CharacterMetadata = __webpack_require__(27); function applyEntityToContentBlock(contentBlock, start, end, entityKey) { var characterList = contentBlock.getCharacterList(); while (start < end) { characterList = characterList.set(start, CharacterMetadata.applyEntity(characterList.get(start), entityKey)); start++; } return contentBlock.set('characterList', characterList); } module.exports = applyEntityToContentBlock; /***/ }), /* 950 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getCharacterRemovalRange * @format * */ var DraftEntitySegments = __webpack_require__(951); var getRangesForDraftEntity = __webpack_require__(952); var invariant = __webpack_require__(10); /** * Given a SelectionState and a removal direction, determine the entire range * that should be removed from a ContentState. This is based on any entities * within the target, with their `mutability` values taken into account. * * For instance, if we are attempting to remove part of an "immutable" entity * range, the entire entity must be removed. The returned `SelectionState` * will be adjusted accordingly. */ function getCharacterRemovalRange(entityMap, startBlock, endBlock, selectionState, direction) { var start = selectionState.getStartOffset(); var end = selectionState.getEndOffset(); var startEntityKey = startBlock.getEntityAt(start); var endEntityKey = endBlock.getEntityAt(end - 1); if (!startEntityKey && !endEntityKey) { return selectionState; } var newSelectionState = selectionState; if (startEntityKey && startEntityKey === endEntityKey) { newSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, true, true); } else if (startEntityKey && endEntityKey) { var startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true); var endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false); newSelectionState = newSelectionState.merge({ anchorOffset: startSelectionState.getAnchorOffset(), focusOffset: endSelectionState.getFocusOffset(), isBackward: false }); } else if (startEntityKey) { var _startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true); newSelectionState = newSelectionState.merge({ anchorOffset: _startSelectionState.getStartOffset(), isBackward: false }); } else if (endEntityKey) { var _endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false); newSelectionState = newSelectionState.merge({ focusOffset: _endSelectionState.getEndOffset(), isBackward: false }); } return newSelectionState; } function getEntityRemovalRange(entityMap, block, selectionState, direction, entityKey, isEntireSelectionWithinEntity, isEntityAtStart) { var start = selectionState.getStartOffset(); var end = selectionState.getEndOffset(); var entity = entityMap.__get(entityKey); var mutability = entity.getMutability(); var sideToConsider = isEntityAtStart ? start : end; // `MUTABLE` entities can just have the specified range of text removed // directly. No adjustments are needed. if (mutability === 'MUTABLE') { return selectionState; } // Find the entity range that overlaps with our removal range. var entityRanges = getRangesForDraftEntity(block, entityKey).filter(function (range) { return sideToConsider <= range.end && sideToConsider >= range.start; }); !(entityRanges.length == 1) ? true ? invariant(false, 'There should only be one entity range within this removal range.') : invariant(false) : void 0; var entityRange = entityRanges[0]; // For `IMMUTABLE` entity types, we will remove the entire entity range. if (mutability === 'IMMUTABLE') { return selectionState.merge({ anchorOffset: entityRange.start, focusOffset: entityRange.end, isBackward: false }); } // For `SEGMENTED` entity types, determine the appropriate segment to // remove. if (!isEntireSelectionWithinEntity) { if (isEntityAtStart) { end = entityRange.end; } else { start = entityRange.start; } } var removalRange = DraftEntitySegments.getRemovalRange(start, end, block.getText().slice(entityRange.start, entityRange.end), entityRange.start, direction); return selectionState.merge({ anchorOffset: removalRange.start, focusOffset: removalRange.end, isBackward: false }); } module.exports = getCharacterRemovalRange; /***/ }), /* 951 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEntitySegments * @format * */ /** * Identify the range to delete from a segmented entity. * * Rules: * * Example: 'John F. Kennedy' * * - Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy']) * will return the range of that text. * * 'John F. Kennedy' -> 'John F.' * ^ * * - Forward deletion of whitespace will remove the following section: * * 'John F. Kennedy' -> 'John Kennedy' * ^ * * - Backward deletion of whitespace will remove the previous section: * * 'John F. Kennedy' -> 'F. Kennedy' * ^ */ var DraftEntitySegments = { getRemovalRange: function getRemovalRange(selectionStart, selectionEnd, text, entityStart, direction) { var segments = text.split(' '); segments = segments.map(function ( /*string*/segment, /*number*/ii) { if (direction === 'forward') { if (ii > 0) { return ' ' + segment; } } else if (ii < segments.length - 1) { return segment + ' '; } return segment; }); var segmentStart = entityStart; var segmentEnd; var segment; var removalStart = null; var removalEnd = null; for (var jj = 0; jj < segments.length; jj++) { segment = segments[jj]; segmentEnd = segmentStart + segment.length; // Our selection overlaps this segment. if (selectionStart < segmentEnd && segmentStart < selectionEnd) { if (removalStart !== null) { removalEnd = segmentEnd; } else { removalStart = segmentStart; removalEnd = segmentEnd; } } else if (removalStart !== null) { break; } segmentStart = segmentEnd; } var entityEnd = entityStart + text.length; var atStart = removalStart === entityStart; var atEnd = removalEnd === entityEnd; if (!atStart && atEnd || atStart && !atEnd) { if (direction === 'forward') { if (removalEnd !== entityEnd) { removalEnd++; } } else if (removalStart !== entityStart) { removalStart--; } } return { start: removalStart, end: removalEnd }; } }; module.exports = DraftEntitySegments; /***/ }), /* 952 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getRangesForDraftEntity * @format * */ var invariant = __webpack_require__(10); /** * Obtain the start and end positions of the range that has the * specified entity applied to it. * * Entity keys are applied only to contiguous stretches of text, so this * method searches for the first instance of the entity key and returns * the subsequent range. */ function getRangesForDraftEntity(block, key) { var ranges = []; block.findEntityRanges(function (c) { return c.getEntity() === key; }, function (start, end) { ranges.push({ start: start, end: end }); }); !!!ranges.length ? true ? invariant(false, 'Entity key not found in this range.') : invariant(false) : void 0; return ranges; } module.exports = getRangesForDraftEntity; /***/ }), /* 953 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule insertFragmentIntoContentState * @format * */ var BlockMapBuilder = __webpack_require__(102); var ContentBlockNode = __webpack_require__(31); var Immutable = __webpack_require__(9); var insertIntoList = __webpack_require__(440); var invariant = __webpack_require__(10); var randomizeBlockMapKeys = __webpack_require__(438); var List = Immutable.List; var updateExistingBlock = function updateExistingBlock(contentState, selectionState, blockMap, fragmentBlock, targetKey, targetOffset) { var targetBlock = blockMap.get(targetKey); var text = targetBlock.getText(); var chars = targetBlock.getCharacterList(); var finalKey = targetKey; var finalOffset = targetOffset + fragmentBlock.getText().length; var newBlock = targetBlock.merge({ text: text.slice(0, targetOffset) + fragmentBlock.getText() + text.slice(targetOffset), characterList: insertIntoList(chars, fragmentBlock.getCharacterList(), targetOffset), data: fragmentBlock.getData() }); return contentState.merge({ blockMap: blockMap.set(targetKey, newBlock), selectionBefore: selectionState, selectionAfter: selectionState.merge({ anchorKey: finalKey, anchorOffset: finalOffset, focusKey: finalKey, focusOffset: finalOffset, isBackward: false }) }); }; /** * Appends text/characterList from the fragment first block to * target block. */ var updateHead = function updateHead(block, targetOffset, fragment) { var text = block.getText(); var chars = block.getCharacterList(); // Modify head portion of block. var headText = text.slice(0, targetOffset); var headCharacters = chars.slice(0, targetOffset); var appendToHead = fragment.first(); return block.merge({ text: headText + appendToHead.getText(), characterList: headCharacters.concat(appendToHead.getCharacterList()), type: headText ? block.getType() : appendToHead.getType(), data: appendToHead.getData() }); }; /** * Appends offset text/characterList from the target block to the last * fragment block. */ var updateTail = function updateTail(block, targetOffset, fragment) { // Modify tail portion of block. var text = block.getText(); var chars = block.getCharacterList(); // Modify head portion of block. var blockSize = text.length; var tailText = text.slice(targetOffset, blockSize); var tailCharacters = chars.slice(targetOffset, blockSize); var prependToTail = fragment.last(); return prependToTail.merge({ text: prependToTail.getText() + tailText, characterList: prependToTail.getCharacterList().concat(tailCharacters), data: prependToTail.getData() }); }; var getRootBlocks = function getRootBlocks(block, blockMap) { var headKey = block.getKey(); var rootBlock = block; var rootBlocks = []; // sometimes the fragment head block will not be part of the blockMap itself this can happen when // the fragment head is used to update the target block, however when this does not happen we need // to make sure that we include it on the rootBlocks since the first block of a fragment is always a // fragment root block if (blockMap.get(headKey)) { rootBlocks.push(headKey); } while (rootBlock && rootBlock.getNextSiblingKey()) { var lastSiblingKey = rootBlock.getNextSiblingKey(); if (!lastSiblingKey) { break; } rootBlocks.push(lastSiblingKey); rootBlock = blockMap.get(lastSiblingKey); } return rootBlocks; }; var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockMap, targetBlock, fragmentHeadBlock) { return blockMap.withMutations(function (blockMapState) { var targetKey = targetBlock.getKey(); var headKey = fragmentHeadBlock.getKey(); var targetNextKey = targetBlock.getNextSiblingKey(); var targetParentKey = targetBlock.getParentKey(); var fragmentRootBlocks = getRootBlocks(fragmentHeadBlock, blockMap); var lastRootFragmentBlockKey = fragmentRootBlocks[fragmentRootBlocks.length - 1]; if (blockMapState.get(headKey)) { // update the fragment head when it is part of the blockMap otherwise blockMapState.setIn([targetKey, 'nextSibling'], headKey); blockMapState.setIn([headKey, 'prevSibling'], targetKey); } else { // update the target block that had the fragment head contents merged into it blockMapState.setIn([targetKey, 'nextSibling'], fragmentHeadBlock.getNextSiblingKey()); blockMapState.setIn([fragmentHeadBlock.getNextSiblingKey(), 'prevSibling'], targetKey); } // update the last root block fragment blockMapState.setIn([lastRootFragmentBlockKey, 'nextSibling'], targetNextKey); // update the original target next block if (targetNextKey) { blockMapState.setIn([targetNextKey, 'prevSibling'], lastRootFragmentBlockKey); } // update fragment parent links fragmentRootBlocks.forEach(function (blockKey) { return blockMapState.setIn([blockKey, 'parent'], targetParentKey); }); // update targetBlock parent child links if (targetParentKey) { var targetParent = blockMap.get(targetParentKey); var originalTargetParentChildKeys = targetParent.getChildKeys(); var targetBlockIndex = originalTargetParentChildKeys.indexOf(targetKey); var insertionIndex = targetBlockIndex + 1; var newChildrenKeysArray = originalTargetParentChildKeys.toArray(); // insert fragment children newChildrenKeysArray.splice.apply(newChildrenKeysArray, [insertionIndex, 0].concat(fragmentRootBlocks)); blockMapState.setIn([targetParentKey, 'children'], List(newChildrenKeysArray)); } }); }; var insertFragment = function insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset) { var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode; var newBlockArr = []; var fragmentSize = fragment.size; var target = blockMap.get(targetKey); var head = fragment.first(); var tail = fragment.last(); var finalOffset = tail.getLength(); var finalKey = tail.getKey(); var shouldNotUpdateFromFragmentBlock = isTreeBasedBlockMap && (!target.getChildKeys().isEmpty() || !head.getChildKeys().isEmpty()); blockMap.forEach(function (block, blockKey) { if (blockKey !== targetKey) { newBlockArr.push(block); return; } if (shouldNotUpdateFromFragmentBlock) { newBlockArr.push(block); } else { newBlockArr.push(updateHead(block, targetOffset, fragment)); } // Insert fragment blocks after the head and before the tail. fragment // when we are updating the target block with the head fragment block we skip the first fragment // head since its contents have already been merged with the target block otherwise we include // the whole fragment .slice(shouldNotUpdateFromFragmentBlock ? 0 : 1, fragmentSize - 1).forEach(function (fragmentBlock) { return newBlockArr.push(fragmentBlock); }); // update tail newBlockArr.push(updateTail(block, targetOffset, fragment)); }); var updatedBlockMap = BlockMapBuilder.createFromArray(newBlockArr); if (isTreeBasedBlockMap) { updatedBlockMap = updateBlockMapLinks(updatedBlockMap, blockMap, target, head); } return contentState.merge({ blockMap: updatedBlockMap, selectionBefore: selectionState, selectionAfter: selectionState.merge({ anchorKey: finalKey, anchorOffset: finalOffset, focusKey: finalKey, focusOffset: finalOffset, isBackward: false }) }); }; var insertFragmentIntoContentState = function insertFragmentIntoContentState(contentState, selectionState, fragmentBlockMap) { !selectionState.isCollapsed() ? true ? invariant(false, '`insertFragment` should only be called with a collapsed selection state.') : invariant(false) : void 0; var blockMap = contentState.getBlockMap(); var fragment = randomizeBlockMapKeys(fragmentBlockMap); var targetKey = selectionState.getStartKey(); var targetOffset = selectionState.getStartOffset(); var targetBlock = blockMap.get(targetKey); if (targetBlock instanceof ContentBlockNode) { !targetBlock.getChildKeys().isEmpty() ? true ? invariant(false, '`insertFragment` should not be called when a container node is selected.') : invariant(false) : void 0; } // When we insert a fragment with a single block we simply update the target block // with the contents of the inserted fragment block if (fragment.size === 1) { return updateExistingBlock(contentState, selectionState, blockMap, fragment.first(), targetKey, targetOffset); } return insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset); }; module.exports = insertFragmentIntoContentState; /***/ }), /* 954 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule insertTextIntoContentState * @format * */ var Immutable = __webpack_require__(9); var insertIntoList = __webpack_require__(440); var invariant = __webpack_require__(10); var Repeat = Immutable.Repeat; function insertTextIntoContentState(contentState, selectionState, text, characterMetadata) { !selectionState.isCollapsed() ? true ? invariant(false, '`insertText` should only be called with a collapsed range.') : invariant(false) : void 0; var len = text.length; if (!len) { return contentState; } var blockMap = contentState.getBlockMap(); var key = selectionState.getStartKey(); var offset = selectionState.getStartOffset(); var block = blockMap.get(key); var blockText = block.getText(); var newBlock = block.merge({ text: blockText.slice(0, offset) + text + blockText.slice(offset, block.getLength()), characterList: insertIntoList(block.getCharacterList(), Repeat(characterMetadata, len).toList(), offset) }); var newOffset = offset + len; return contentState.merge({ blockMap: blockMap.set(key, newBlock), selectionAfter: selectionState.merge({ anchorOffset: newOffset, focusOffset: newOffset }) }); } module.exports = insertTextIntoContentState; /***/ }), /* 955 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule modifyBlockForContentState * @format * */ var Immutable = __webpack_require__(9); var Map = Immutable.Map; function modifyBlockForContentState(contentState, selectionState, operation) { var startKey = selectionState.getStartKey(); var endKey = selectionState.getEndKey(); var blockMap = contentState.getBlockMap(); var newBlocks = blockMap.toSeq().skipUntil(function (_, k) { return k === startKey; }).takeUntil(function (_, k) { return k === endKey; }).concat(Map([[endKey, blockMap.get(endKey)]])).map(operation); return contentState.merge({ blockMap: blockMap.merge(newBlocks), selectionBefore: selectionState, selectionAfter: selectionState }); } module.exports = modifyBlockForContentState; /***/ }), /* 956 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule removeRangeFromContentState * @format * */ var ContentBlockNode = __webpack_require__(31); var Immutable = __webpack_require__(9); var getNextDelimiterBlockKey = __webpack_require__(441); var List = Immutable.List, Map = Immutable.Map; var transformBlock = function transformBlock(key, blockMap, func) { if (!key) { return; } var block = blockMap.get(key); if (!block) { return; } blockMap.set(key, func(block)); }; /** * Ancestors needs to be preserved when there are non selected * children to make sure we do not leave any orphans behind */ var getAncestorsKeys = function getAncestorsKeys(blockKey, blockMap) { var parents = []; if (!blockKey) { return parents; } var blockNode = blockMap.get(blockKey); while (blockNode && blockNode.getParentKey()) { var parentKey = blockNode.getParentKey(); if (parentKey) { parents.push(parentKey); } blockNode = parentKey ? blockMap.get(parentKey) : null; } return parents; }; /** * Get all next delimiter keys until we hit a root delimiter and return * an array of key references */ var getNextDelimitersBlockKeys = function getNextDelimitersBlockKeys(block, blockMap) { var nextDelimiters = []; if (!block) { return nextDelimiters; } var nextDelimiter = getNextDelimiterBlockKey(block, blockMap); while (nextDelimiter && blockMap.get(nextDelimiter)) { var _block = blockMap.get(nextDelimiter); nextDelimiters.push(nextDelimiter); // we do not need to keep checking all root node siblings, just the first occurance nextDelimiter = _block.getParentKey() ? getNextDelimiterBlockKey(_block, blockMap) : null; } return nextDelimiters; }; var getNextValidSibling = function getNextValidSibling(block, blockMap, originalBlockMap) { if (!block) { return null; } // note that we need to make sure we refer to the original block since this // function is called within a withMutations var nextValidSiblingKey = originalBlockMap.get(block.getKey()).getNextSiblingKey(); while (nextValidSiblingKey && !blockMap.get(nextValidSiblingKey)) { nextValidSiblingKey = originalBlockMap.get(nextValidSiblingKey).getNextSiblingKey() || null; } return nextValidSiblingKey; }; var getPrevValidSibling = function getPrevValidSibling(block, blockMap, originalBlockMap) { if (!block) { return null; } // note that we need to make sure we refer to the original block since this // function is called within a withMutations var prevValidSiblingKey = originalBlockMap.get(block.getKey()).getPrevSiblingKey(); while (prevValidSiblingKey && !blockMap.get(prevValidSiblingKey)) { prevValidSiblingKey = originalBlockMap.get(prevValidSiblingKey).getPrevSiblingKey() || null; } return prevValidSiblingKey; }; var updateBlockMapLinks = function updateBlockMapLinks(blockMap, startBlock, endBlock, originalBlockMap) { return blockMap.withMutations(function (blocks) { // update start block if its retained transformBlock(startBlock.getKey(), blocks, function (block) { return block.merge({ nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap), prevSibling: getPrevValidSibling(startBlock, blocks, originalBlockMap) }); }); // update endblock if its retained transformBlock(endBlock.getKey(), blocks, function (block) { return block.merge({ nextSibling: getNextValidSibling(endBlock, blocks, originalBlockMap), prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap) }); }); // update start block parent ancestors getAncestorsKeys(startBlock.getKey(), originalBlockMap).forEach(function (parentKey) { return transformBlock(parentKey, blocks, function (block) { return block.merge({ children: block.getChildKeys().filter(function (key) { return blocks.get(key); }), nextSibling: getNextValidSibling(block, blocks, originalBlockMap), prevSibling: getPrevValidSibling(block, blocks, originalBlockMap) }); }); }); // update start block next - can only happen if startBlock == endBlock transformBlock(startBlock.getNextSiblingKey(), blocks, function (block) { return block.merge({ prevSibling: startBlock.getPrevSiblingKey() }); }); // update start block prev transformBlock(startBlock.getPrevSiblingKey(), blocks, function (block) { return block.merge({ nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap) }); }); // update end block next transformBlock(endBlock.getNextSiblingKey(), blocks, function (block) { return block.merge({ prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap) }); }); // update end block prev transformBlock(endBlock.getPrevSiblingKey(), blocks, function (block) { return block.merge({ nextSibling: endBlock.getNextSiblingKey() }); }); // update end block parent ancestors getAncestorsKeys(endBlock.getKey(), originalBlockMap).forEach(function (parentKey) { transformBlock(parentKey, blocks, function (block) { return block.merge({ children: block.getChildKeys().filter(function (key) { return blocks.get(key); }), nextSibling: getNextValidSibling(block, blocks, originalBlockMap), prevSibling: getPrevValidSibling(block, blocks, originalBlockMap) }); }); }); // update next delimiters all the way to a root delimiter getNextDelimitersBlockKeys(endBlock, originalBlockMap).forEach(function (delimiterKey) { return transformBlock(delimiterKey, blocks, function (block) { return block.merge({ nextSibling: getNextValidSibling(block, blocks, originalBlockMap), prevSibling: getPrevValidSibling(block, blocks, originalBlockMap) }); }); }); }); }; var removeRangeFromContentState = function removeRangeFromContentState(contentState, selectionState) { if (selectionState.isCollapsed()) { return contentState; } var blockMap = contentState.getBlockMap(); var startKey = selectionState.getStartKey(); var startOffset = selectionState.getStartOffset(); var endKey = selectionState.getEndKey(); var endOffset = selectionState.getEndOffset(); var startBlock = blockMap.get(startKey); var endBlock = blockMap.get(endKey); // we assume that ContentBlockNode and ContentBlocks are not mixed together var isExperimentalTreeBlock = startBlock instanceof ContentBlockNode; // used to retain blocks that should not be deleted to avoid orphan children var parentAncestors = []; if (isExperimentalTreeBlock) { var endBlockchildrenKeys = endBlock.getChildKeys(); var endBlockAncestors = getAncestorsKeys(endKey, blockMap); // endBlock has unselected sibblings so we can not remove its ancestors parents if (endBlock.getNextSiblingKey()) { parentAncestors = parentAncestors.concat(endBlockAncestors); } // endBlock has children so can not remove this block or any of its ancestors if (!endBlockchildrenKeys.isEmpty()) { parentAncestors = parentAncestors.concat(endBlockAncestors.concat([endKey])); } // we need to retain all ancestors of the next delimiter block parentAncestors = parentAncestors.concat(getAncestorsKeys(getNextDelimiterBlockKey(endBlock, blockMap), blockMap)); } var characterList = void 0; if (startBlock === endBlock) { characterList = removeFromList(startBlock.getCharacterList(), startOffset, endOffset); } else { characterList = startBlock.getCharacterList().slice(0, startOffset).concat(endBlock.getCharacterList().slice(endOffset)); } var modifiedStart = startBlock.merge({ text: startBlock.getText().slice(0, startOffset) + endBlock.getText().slice(endOffset), characterList: characterList }); var newBlocks = blockMap.toSeq().skipUntil(function (_, k) { return k === startKey; }).takeUntil(function (_, k) { return k === endKey; }).filter(function (_, k) { return parentAncestors.indexOf(k) === -1; }).concat(Map([[endKey, null]])).map(function (_, k) { return k === startKey ? modifiedStart : null; }); var updatedBlockMap = blockMap.merge(newBlocks).filter(function (block) { return !!block; }); if (isExperimentalTreeBlock) { updatedBlockMap = updateBlockMapLinks(updatedBlockMap, startBlock, endBlock, blockMap); } return contentState.merge({ blockMap: updatedBlockMap, selectionBefore: selectionState, selectionAfter: selectionState.merge({ anchorKey: startKey, anchorOffset: startOffset, focusKey: startKey, focusOffset: startOffset, isBackward: false }) }); }; /** * Maintain persistence for target list when removing characters on the * head and tail of the character list. */ var removeFromList = function removeFromList(targetList, startOffset, endOffset) { if (startOffset === 0) { while (startOffset < endOffset) { targetList = targetList.shift(); startOffset++; } } else if (endOffset === targetList.count()) { while (endOffset > startOffset) { targetList = targetList.pop(); endOffset--; } } else { var head = targetList.slice(0, startOffset); var tail = targetList.slice(endOffset); targetList = head.concat(tail).toList(); } return targetList; }; module.exports = removeRangeFromContentState; /***/ }), /* 957 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule splitBlockInContentState * @format * */ var ContentBlockNode = __webpack_require__(31); var Immutable = __webpack_require__(9); var generateRandomKey = __webpack_require__(50); var invariant = __webpack_require__(10); var List = Immutable.List, Map = Immutable.Map; var transformBlock = function transformBlock(key, blockMap, func) { if (!key) { return; } var block = blockMap.get(key); if (!block) { return; } blockMap.set(key, func(block)); }; var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlock, belowBlock) { return blockMap.withMutations(function (blocks) { var originalBlockKey = originalBlock.getKey(); var belowBlockKey = belowBlock.getKey(); // update block parent transformBlock(originalBlock.getParentKey(), blocks, function (block) { var parentChildrenList = block.getChildKeys(); var insertionIndex = parentChildrenList.indexOf(originalBlockKey) + 1; var newChildrenArray = parentChildrenList.toArray(); newChildrenArray.splice(insertionIndex, 0, belowBlockKey); return block.merge({ children: List(newChildrenArray) }); }); // update original next block transformBlock(originalBlock.getNextSiblingKey(), blocks, function (block) { return block.merge({ prevSibling: belowBlockKey }); }); // update original block transformBlock(originalBlockKey, blocks, function (block) { return block.merge({ nextSibling: belowBlockKey }); }); // update below block transformBlock(belowBlockKey, blocks, function (block) { return block.merge({ prevSibling: originalBlockKey }); }); }); }; var splitBlockInContentState = function splitBlockInContentState(contentState, selectionState) { !selectionState.isCollapsed() ? true ? invariant(false, 'Selection range must be collapsed.') : invariant(false) : void 0; var key = selectionState.getAnchorKey(); var offset = selectionState.getAnchorOffset(); var blockMap = contentState.getBlockMap(); var blockToSplit = blockMap.get(key); var text = blockToSplit.getText(); var chars = blockToSplit.getCharacterList(); var keyBelow = generateRandomKey(); var isExperimentalTreeBlock = blockToSplit instanceof ContentBlockNode; var blockAbove = blockToSplit.merge({ text: text.slice(0, offset), characterList: chars.slice(0, offset) }); var blockBelow = blockAbove.merge({ key: keyBelow, text: text.slice(offset), characterList: chars.slice(offset), data: Map() }); var blocksBefore = blockMap.toSeq().takeUntil(function (v) { return v === blockToSplit; }); var blocksAfter = blockMap.toSeq().skipUntil(function (v) { return v === blockToSplit; }).rest(); var newBlocks = blocksBefore.concat([[key, blockAbove], [keyBelow, blockBelow]], blocksAfter).toOrderedMap(); if (isExperimentalTreeBlock) { !blockToSplit.getChildKeys().isEmpty() ? true ? invariant(false, 'ContentBlockNode must not have children') : invariant(false) : void 0; newBlocks = updateBlockMapLinks(newBlocks, blockAbove, blockBelow); } return contentState.merge({ blockMap: newBlocks, selectionBefore: selectionState, selectionAfter: selectionState.merge({ anchorKey: keyBelow, anchorOffset: 0, focusKey: keyBelow, focusOffset: 0, isBackward: false }) }); }; module.exports = splitBlockInContentState; /***/ }), /* 958 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EditorBidiService * @format * */ var Immutable = __webpack_require__(9); var UnicodeBidiService = __webpack_require__(959); var nullthrows = __webpack_require__(35); var OrderedMap = Immutable.OrderedMap; var bidiService; var EditorBidiService = { getDirectionMap: function getDirectionMap(content, prevBidiMap) { if (!bidiService) { bidiService = new UnicodeBidiService(); } else { bidiService.reset(); } var blockMap = content.getBlockMap(); var nextBidi = blockMap.valueSeq().map(function (block) { return nullthrows(bidiService).getDirection(block.getText()); }); var bidiMap = OrderedMap(blockMap.keySeq().zip(nextBidi)); if (prevBidiMap != null && Immutable.is(prevBidiMap, bidiMap)) { return prevBidiMap; } return bidiMap; } }; module.exports = EditorBidiService; /***/ }), /* 959 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks * */ /** * Stateful API for text direction detection * * This class can be used in applications where you need to detect the * direction of a sequence of text blocks, where each direction shall be used * as the fallback direction for the next one. * * NOTE: A default direction, if not provided, is set based on the global * direction, as defined by `UnicodeBidiDirection`. * * == Example == * ``` * var UnicodeBidiService = require('UnicodeBidiService'); * * var bidiService = new UnicodeBidiService(); * * ... * * bidiService.reset(); * for (var para in paragraphs) { * var dir = bidiService.getDirection(para); * ... * } * ``` * * Part of our implementation of Unicode Bidirectional Algorithm (UBA) * Unicode Standard Annex #9 (UAX9) * http://www.unicode.org/reports/tr9/ */ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var UnicodeBidi = __webpack_require__(444); var UnicodeBidiDirection = __webpack_require__(191); var invariant = __webpack_require__(10); var UnicodeBidiService = function () { /** * Stateful class for paragraph direction detection * * @param defaultDir Default direction of the service */ function UnicodeBidiService(defaultDir) { _classCallCheck(this, UnicodeBidiService); if (!defaultDir) { defaultDir = UnicodeBidiDirection.getGlobalDir(); } else { !UnicodeBidiDirection.isStrong(defaultDir) ? true ? invariant(false, 'Default direction must be a strong direction (LTR or RTL)') : invariant(false) : void 0; } this._defaultDir = defaultDir; this.reset(); } /** * Reset the internal state * * Instead of creating a new instance, you can just reset() your instance * everytime you start a new loop. */ UnicodeBidiService.prototype.reset = function reset() { this._lastDir = this._defaultDir; }; /** * Returns the direction of a block of text, and remembers it as the * fall-back direction for the next paragraph. * * @param str A text block, e.g. paragraph, table cell, tag * @return The resolved direction */ UnicodeBidiService.prototype.getDirection = function getDirection(str) { this._lastDir = UnicodeBidi.getDirection(str, this._lastDir); return this._lastDir; }; return UnicodeBidiService; }(); module.exports = UnicodeBidiService; /***/ }), /* 960 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule moveBlockInContentState * @format * */ var ContentBlockNode = __webpack_require__(31); var Immutable = __webpack_require__(9); var getNextDelimiterBlockKey = __webpack_require__(441); var invariant = __webpack_require__(10); var OrderedMap = Immutable.OrderedMap, List = Immutable.List; var transformBlock = function transformBlock(key, blockMap, func) { if (!key) { return; } var block = blockMap.get(key); if (!block) { return; } blockMap.set(key, func(block)); }; var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockToBeMoved, originalTargetBlock, insertionMode, isExperimentalTreeBlock) { if (!isExperimentalTreeBlock) { return blockMap; } // possible values of 'insertionMode' are: 'after', 'before' var isInsertedAfterTarget = insertionMode === 'after'; var originalBlockKey = originalBlockToBeMoved.getKey(); var originalTargetKey = originalTargetBlock.getKey(); var originalParentKey = originalBlockToBeMoved.getParentKey(); var originalNextSiblingKey = originalBlockToBeMoved.getNextSiblingKey(); var originalPrevSiblingKey = originalBlockToBeMoved.getPrevSiblingKey(); var newParentKey = originalTargetBlock.getParentKey(); var newNextSiblingKey = isInsertedAfterTarget ? originalTargetBlock.getNextSiblingKey() : originalTargetKey; var newPrevSiblingKey = isInsertedAfterTarget ? originalTargetKey : originalTargetBlock.getPrevSiblingKey(); return blockMap.withMutations(function (blocks) { // update old parent transformBlock(originalParentKey, blocks, function (block) { var parentChildrenList = block.getChildKeys(); return block.merge({ children: parentChildrenList['delete'](parentChildrenList.indexOf(originalBlockKey)) }); }); // update old prev transformBlock(originalPrevSiblingKey, blocks, function (block) { return block.merge({ nextSibling: originalNextSiblingKey }); }); // update old next transformBlock(originalNextSiblingKey, blocks, function (block) { return block.merge({ prevSibling: originalPrevSiblingKey }); }); // update new next transformBlock(newNextSiblingKey, blocks, function (block) { return block.merge({ prevSibling: originalBlockKey }); }); // update new prev transformBlock(newPrevSiblingKey, blocks, function (block) { return block.merge({ nextSibling: originalBlockKey }); }); // update new parent transformBlock(newParentKey, blocks, function (block) { var newParentChildrenList = block.getChildKeys(); var targetBlockIndex = newParentChildrenList.indexOf(originalTargetKey); var insertionIndex = isInsertedAfterTarget ? targetBlockIndex + 1 : targetBlockIndex !== 0 ? targetBlockIndex - 1 : 0; var newChildrenArray = newParentChildrenList.toArray(); newChildrenArray.splice(insertionIndex, 0, originalBlockKey); return block.merge({ children: List(newChildrenArray) }); }); // update block transformBlock(originalBlockKey, blocks, function (block) { return block.merge({ nextSibling: newNextSiblingKey, prevSibling: newPrevSiblingKey, parent: newParentKey }); }); }); }; var moveBlockInContentState = function moveBlockInContentState(contentState, blockToBeMoved, targetBlock, insertionMode) { !(insertionMode !== 'replace') ? true ? invariant(false, 'Replacing blocks is not supported.') : invariant(false) : void 0; var targetKey = targetBlock.getKey(); var blockKey = blockToBeMoved.getKey(); !(blockKey !== targetKey) ? true ? invariant(false, 'Block cannot be moved next to itself.') : invariant(false) : void 0; var blockMap = contentState.getBlockMap(); var isExperimentalTreeBlock = blockToBeMoved instanceof ContentBlockNode; var blocksToBeMoved = [blockToBeMoved]; var blockMapWithoutBlocksToBeMoved = blockMap['delete'](blockKey); if (isExperimentalTreeBlock) { blocksToBeMoved = []; blockMapWithoutBlocksToBeMoved = blockMap.withMutations(function (blocks) { var nextSiblingKey = blockToBeMoved.getNextSiblingKey(); var nextDelimiterBlockKey = getNextDelimiterBlockKey(blockToBeMoved, blocks); blocks.toSeq().skipUntil(function (block) { return block.getKey() === blockKey; }).takeWhile(function (block) { var key = block.getKey(); var isBlockToBeMoved = key === blockKey; var hasNextSiblingAndIsNotNextSibling = nextSiblingKey && key !== nextSiblingKey; var doesNotHaveNextSiblingAndIsNotDelimiter = !nextSiblingKey && block.getParentKey() && (!nextDelimiterBlockKey || key !== nextDelimiterBlockKey); return !!(isBlockToBeMoved || hasNextSiblingAndIsNotNextSibling || doesNotHaveNextSiblingAndIsNotDelimiter); }).forEach(function (block) { blocksToBeMoved.push(block); blocks['delete'](block.getKey()); }); }); } var blocksBefore = blockMapWithoutBlocksToBeMoved.toSeq().takeUntil(function (v) { return v === targetBlock; }); var blocksAfter = blockMapWithoutBlocksToBeMoved.toSeq().skipUntil(function (v) { return v === targetBlock; }).skip(1); var slicedBlocks = blocksToBeMoved.map(function (block) { return [block.getKey(), block]; }); var newBlocks = OrderedMap(); if (insertionMode === 'before') { var blockBefore = contentState.getBlockBefore(targetKey); !(!blockBefore || blockBefore.getKey() !== blockToBeMoved.getKey()) ? true ? invariant(false, 'Block cannot be moved next to itself.') : invariant(false) : void 0; newBlocks = blocksBefore.concat([].concat(slicedBlocks, [[targetKey, targetBlock]]), blocksAfter).toOrderedMap(); } else if (insertionMode === 'after') { var blockAfter = contentState.getBlockAfter(targetKey); !(!blockAfter || blockAfter.getKey() !== blockKey) ? true ? invariant(false, 'Block cannot be moved next to itself.') : invariant(false) : void 0; newBlocks = blocksBefore.concat([[targetKey, targetBlock]].concat(slicedBlocks), blocksAfter).toOrderedMap(); } return contentState.merge({ blockMap: updateBlockMapLinks(newBlocks, blockToBeMoved, targetBlock, insertionMode, isExperimentalTreeBlock), selectionBefore: contentState.getSelectionAfter(), selectionAfter: contentState.getSelectionAfter().merge({ anchorKey: blockKey, focusKey: blockKey }) }); }; module.exports = moveBlockInContentState; /***/ }), /* 961 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CompositeDraftDecorator * @format * */ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Immutable = __webpack_require__(9); var List = Immutable.List; var DELIMITER = '.'; /** * A CompositeDraftDecorator traverses through a list of DraftDecorator * instances to identify sections of a ContentBlock that should be rendered * in a "decorated" manner. For example, hashtags, mentions, and links may * be intended to stand out visually, be rendered as anchors, etc. * * The list of decorators supplied to the constructor will be used in the * order they are provided. This allows the caller to specify a priority for * string matching, in case of match collisions among decorators. * * For instance, I may have a link with a `#` in its text. Though this section * of text may match our hashtag decorator, it should not be treated as a * hashtag. I should therefore list my link DraftDecorator * before my hashtag DraftDecorator when constructing this composite * decorator instance. * * Thus, when a collision like this is encountered, the earlier match is * preserved and the new match is discarded. */ var CompositeDraftDecorator = function () { function CompositeDraftDecorator(decorators) { _classCallCheck(this, CompositeDraftDecorator); // Copy the decorator array, since we use this array order to determine // precedence of decoration matching. If the array is mutated externally, // we don't want to be affected here. this._decorators = decorators.slice(); } CompositeDraftDecorator.prototype.getDecorations = function getDecorations(block, contentState) { var decorations = Array(block.getText().length).fill(null); this._decorators.forEach(function ( /*object*/decorator, /*number*/ii) { var counter = 0; var strategy = decorator.strategy; var callback = function callback( /*number*/start, /*number*/end) { // Find out if any of our matching range is already occupied // by another decorator. If so, discard the match. Otherwise, store // the component key for rendering. if (canOccupySlice(decorations, start, end)) { occupySlice(decorations, start, end, ii + DELIMITER + counter); counter++; } }; strategy(block, callback, contentState); }); return List(decorations); }; CompositeDraftDecorator.prototype.getComponentForKey = function getComponentForKey(key) { var componentKey = parseInt(key.split(DELIMITER)[0], 10); return this._decorators[componentKey].component; }; CompositeDraftDecorator.prototype.getPropsForKey = function getPropsForKey(key) { var componentKey = parseInt(key.split(DELIMITER)[0], 10); return this._decorators[componentKey].props; }; return CompositeDraftDecorator; }(); /** * Determine whether we can occupy the specified slice of the decorations * array. */ function canOccupySlice(decorations, start, end) { for (var ii = start; ii < end; ii++) { if (decorations[ii] != null) { return false; } } return true; } /** * Splice the specified component into our decoration array at the desired * range. */ function occupySlice(targetArr, start, end, componentKey) { for (var ii = start; ii < end; ii++) { targetArr[ii] = componentKey; } } module.exports = CompositeDraftDecorator; /***/ }), /* 962 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditor.react * @format * * @preventMunge */ var _assign = __webpack_require__(18); var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DefaultDraftBlockRenderMap = __webpack_require__(192); var DefaultDraftInlineStyle = __webpack_require__(445); var DraftEditorCompositionHandler = __webpack_require__(963); var DraftEditorContents = __webpack_require__(964); var DraftEditorDragHandler = __webpack_require__(987); var DraftEditorEditHandler = __webpack_require__(990); var DraftEditorPlaceholder = __webpack_require__(1023); var EditorState = __webpack_require__(15); var React = __webpack_require__(0); var ReactDOM = __webpack_require__(8); var Scroll = __webpack_require__(449); var Style = __webpack_require__(196); var UserAgent = __webpack_require__(44); var cx = __webpack_require__(85); var emptyFunction = __webpack_require__(113); var generateRandomKey = __webpack_require__(50); var getDefaultKeyBinding = __webpack_require__(462); var getScrollPosition = __webpack_require__(197); var invariant = __webpack_require__(10); var nullthrows = __webpack_require__(35); var isIE = UserAgent.isBrowser('IE'); // IE does not support the `input` event on contentEditable, so we can't // observe spellcheck behavior. var allowSpellCheck = !isIE; // Define a set of handler objects to correspond to each possible `mode` // of editor behavior. var handlerMap = { edit: DraftEditorEditHandler, composite: DraftEditorCompositionHandler, drag: DraftEditorDragHandler, cut: null, render: null }; /** * `DraftEditor` is the root editor component. It composes a `contentEditable` * div, and provides a wide variety of useful function props for managing the * state of the editor. See `DraftEditorProps` for details. */ var DraftEditor = function (_React$Component) { _inherits(DraftEditor, _React$Component); function DraftEditor(props) { _classCallCheck(this, DraftEditor); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.focus = function (scrollPosition) { var editorState = _this.props.editorState; var alreadyHasFocus = editorState.getSelection().getHasFocus(); var editorNode = ReactDOM.findDOMNode(_this.editor); if (!editorNode) { // once in a while people call 'focus' in a setTimeout, and the node has // been deleted, so it can be null in that case. return; } var scrollParent = Style.getScrollParent(editorNode); var _ref = scrollPosition || getScrollPosition(scrollParent), x = _ref.x, y = _ref.y; !(editorNode instanceof HTMLElement) ? true ? invariant(false, 'editorNode is not an HTMLElement') : invariant(false) : void 0; editorNode.focus(); // Restore scroll position if (scrollParent === window) { window.scrollTo(x, y); } else { Scroll.setTop(scrollParent, y); } // On Chrome and Safari, calling focus on contenteditable focuses the // cursor at the first character. This is something you don't expect when // you're clicking on an input element but not directly on a character. // Put the cursor back where it was before the blur. if (!alreadyHasFocus) { _this.update(EditorState.forceSelection(editorState, editorState.getSelection())); } }; _this.blur = function () { var editorNode = ReactDOM.findDOMNode(_this.editor); !(editorNode instanceof HTMLElement) ? true ? invariant(false, 'editorNode is not an HTMLElement') : invariant(false) : void 0; editorNode.blur(); }; _this.setMode = function (mode) { _this._handler = handlerMap[mode]; }; _this.exitCurrentMode = function () { _this.setMode('edit'); }; _this.restoreEditorDOM = function (scrollPosition) { _this.setState({ contentsKey: _this.state.contentsKey + 1 }, function () { _this.focus(scrollPosition); }); }; _this.setClipboard = function (clipboard) { _this._clipboard = clipboard; }; _this.getClipboard = function () { return _this._clipboard; }; _this.update = function (editorState) { _this._latestEditorState = editorState; _this.props.onChange(editorState); }; _this.onDragEnter = function () { _this._dragCount++; }; _this.onDragLeave = function () { _this._dragCount--; if (_this._dragCount === 0) { _this.exitCurrentMode(); } }; _this._blockSelectEvents = false; _this._clipboard = null; _this._handler = null; _this._dragCount = 0; _this._editorKey = props.editorKey || generateRandomKey(); _this._placeholderAccessibilityID = 'placeholder-' + _this._editorKey; _this._latestEditorState = props.editorState; _this._latestCommittedEditorState = props.editorState; _this._onBeforeInput = _this._buildHandler('onBeforeInput'); _this._onBlur = _this._buildHandler('onBlur'); _this._onCharacterData = _this._buildHandler('onCharacterData'); _this._onCompositionEnd = _this._buildHandler('onCompositionEnd'); _this._onCompositionStart = _this._buildHandler('onCompositionStart'); _this._onCopy = _this._buildHandler('onCopy'); _this._onCut = _this._buildHandler('onCut'); _this._onDragEnd = _this._buildHandler('onDragEnd'); _this._onDragOver = _this._buildHandler('onDragOver'); _this._onDragStart = _this._buildHandler('onDragStart'); _this._onDrop = _this._buildHandler('onDrop'); _this._onInput = _this._buildHandler('onInput'); _this._onFocus = _this._buildHandler('onFocus'); _this._onKeyDown = _this._buildHandler('onKeyDown'); _this._onKeyPress = _this._buildHandler('onKeyPress'); _this._onKeyUp = _this._buildHandler('onKeyUp'); _this._onMouseDown = _this._buildHandler('onMouseDown'); _this._onMouseUp = _this._buildHandler('onMouseUp'); _this._onPaste = _this._buildHandler('onPaste'); _this._onSelect = _this._buildHandler('onSelect'); _this.getEditorKey = function () { return _this._editorKey; }; // See `restoreEditorDOM()`. _this.state = { contentsKey: 0 }; return _this; } /** * Build a method that will pass the event to the specified handler method. * This allows us to look up the correct handler function for the current * editor mode, if any has been specified. */ /** * Define proxies that can route events to the current handler. */ DraftEditor.prototype._buildHandler = function _buildHandler(eventName) { var _this2 = this; return function (e) { if (!_this2.props.readOnly) { var method = _this2._handler && _this2._handler[eventName]; method && method(_this2, e); } }; }; DraftEditor.prototype._showPlaceholder = function _showPlaceholder() { return !!this.props.placeholder && !this.props.editorState.isInCompositionMode() && !this.props.editorState.getCurrentContent().hasText(); }; DraftEditor.prototype._renderPlaceholder = function _renderPlaceholder() { if (this._showPlaceholder()) { var placeHolderProps = { text: nullthrows(this.props.placeholder), editorState: this.props.editorState, textAlignment: this.props.textAlignment, accessibilityID: this._placeholderAccessibilityID }; return React.createElement(DraftEditorPlaceholder, placeHolderProps); } return null; }; DraftEditor.prototype.render = function render() { var _this3 = this; var _props = this.props, blockRenderMap = _props.blockRenderMap, blockRendererFn = _props.blockRendererFn, blockStyleFn = _props.blockStyleFn, customStyleFn = _props.customStyleFn, customStyleMap = _props.customStyleMap, editorState = _props.editorState, readOnly = _props.readOnly, textAlignment = _props.textAlignment, textDirectionality = _props.textDirectionality; var rootClass = cx({ 'DraftEditor/root': true, 'DraftEditor/alignLeft': textAlignment === 'left', 'DraftEditor/alignRight': textAlignment === 'right', 'DraftEditor/alignCenter': textAlignment === 'center' }); var contentStyle = { outline: 'none', // fix parent-draggable Safari bug. #1326 userSelect: 'text', WebkitUserSelect: 'text', whiteSpace: 'pre-wrap', wordWrap: 'break-word' }; // The aria-expanded and aria-haspopup properties should only be rendered // for a combobox. var ariaRole = this.props.role || 'textbox'; var ariaExpanded = ariaRole === 'combobox' ? !!this.props.ariaExpanded : null; var editorContentsProps = { blockRenderMap: blockRenderMap, blockRendererFn: blockRendererFn, blockStyleFn: blockStyleFn, customStyleMap: _extends({}, DefaultDraftInlineStyle, customStyleMap), customStyleFn: customStyleFn, editorKey: this._editorKey, editorState: editorState, key: 'contents' + this.state.contentsKey, textDirectionality: textDirectionality }; return React.createElement( 'div', { className: rootClass }, this._renderPlaceholder(), React.createElement( 'div', { className: cx('DraftEditor/editorContainer'), ref: function ref(_ref3) { return _this3.editorContainer = _ref3; } }, React.createElement( 'div', { 'aria-activedescendant': readOnly ? null : this.props.ariaActiveDescendantID, 'aria-autocomplete': readOnly ? null : this.props.ariaAutoComplete, 'aria-controls': readOnly ? null : this.props.ariaControls, 'aria-describedby': this.props.ariaDescribedBy || this._placeholderAccessibilityID, 'aria-expanded': readOnly ? null : ariaExpanded, 'aria-label': this.props.ariaLabel, 'aria-labelledby': this.props.ariaLabelledBy, 'aria-multiline': this.props.ariaMultiline, autoCapitalize: this.props.autoCapitalize, autoComplete: this.props.autoComplete, autoCorrect: this.props.autoCorrect, className: cx({ // Chrome's built-in translation feature mutates the DOM in ways // that Draft doesn't expect (ex: adding tags inside // DraftEditorLeaf spans) and causes problems. We add notranslate // here which makes its autotranslation skip over this subtree. notranslate: !readOnly, 'public/DraftEditor/content': true }), contentEditable: !readOnly, 'data-testid': this.props.webDriverTestID, onBeforeInput: this._onBeforeInput, onBlur: this._onBlur, onCompositionEnd: this._onCompositionEnd, onCompositionStart: this._onCompositionStart, onCopy: this._onCopy, onCut: this._onCut, onDragEnd: this._onDragEnd, onDragEnter: this.onDragEnter, onDragLeave: this.onDragLeave, onDragOver: this._onDragOver, onDragStart: this._onDragStart, onDrop: this._onDrop, onFocus: this._onFocus, onInput: this._onInput, onKeyDown: this._onKeyDown, onKeyPress: this._onKeyPress, onKeyUp: this._onKeyUp, onMouseUp: this._onMouseUp, onPaste: this._onPaste, onSelect: this._onSelect, ref: function ref(_ref2) { return _this3.editor = _ref2; }, role: readOnly ? null : ariaRole, spellCheck: allowSpellCheck && this.props.spellCheck, style: contentStyle, suppressContentEditableWarning: true, tabIndex: this.props.tabIndex }, React.createElement(DraftEditorContents, editorContentsProps) ) ) ); }; DraftEditor.prototype.componentDidMount = function componentDidMount() { this.setMode('edit'); /** * IE has a hardcoded "feature" that attempts to convert link text into * anchors in contentEditable DOM. This breaks the editor's expectations of * the DOM, and control is lost. Disable it to make IE behave. * See: http://blogs.msdn.com/b/ieinternals/archive/2010/09/15/ * ie9-beta-minor-change-list.aspx */ if (isIE) { document.execCommand('AutoUrlDetect', false, false); } }; /** * Prevent selection events from affecting the current editor state. This * is mostly intended to defend against IE, which fires off `selectionchange` * events regardless of whether the selection is set via the browser or * programmatically. We only care about selection events that occur because * of browser interaction, not re-renders and forced selections. */ DraftEditor.prototype.componentWillUpdate = function componentWillUpdate(nextProps) { this._blockSelectEvents = true; this._latestEditorState = nextProps.editorState; }; DraftEditor.prototype.componentDidUpdate = function componentDidUpdate() { this._blockSelectEvents = false; this._latestCommittedEditorState = this.props.editorState; }; /** * Used via `this.focus()`. * * Force focus back onto the editor node. * * We attempt to preserve scroll position when focusing. You can also pass * a specified scroll position (for cases like `cut` behavior where it should * be restored to a known position). */ /** * Used via `this.setMode(...)`. * * Set the behavior mode for the editor component. This switches the current * handler module to ensure that DOM events are managed appropriately for * the active mode. */ /** * Used via `this.restoreEditorDOM()`. * * Force a complete re-render of the DraftEditorContents based on the current * EditorState. This is useful when we know we are going to lose control of * the DOM state (cut command, IME) and we want to make sure that * reconciliation occurs on a version of the DOM that is synchronized with * our EditorState. */ /** * Used via `this.setClipboard(...)`. * * Set the clipboard state for a cut/copy event. */ /** * Used via `this.getClipboard()`. * * Retrieve the clipboard state for a cut/copy event. */ /** * Used via `this.update(...)`. * * Propagate a new `EditorState` object to higher-level components. This is * the method by which event handlers inform the `DraftEditor` component of * state changes. A component that composes a `DraftEditor` **must** provide * an `onChange` prop to receive state updates passed along from this * function. */ /** * Used in conjunction with `onDragLeave()`, by counting the number of times * a dragged element enters and leaves the editor (or any of its children), * to determine when the dragged element absolutely leaves the editor. */ /** * See `onDragEnter()`. */ return DraftEditor; }(React.Component); DraftEditor.defaultProps = { blockRenderMap: DefaultDraftBlockRenderMap, blockRendererFn: emptyFunction.thatReturnsNull, blockStyleFn: emptyFunction.thatReturns(''), keyBindingFn: getDefaultKeyBinding, readOnly: false, spellCheck: false, stripPastedStyles: false }; module.exports = DraftEditor; /***/ }), /* 963 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorCompositionHandler * @format * */ var DraftFeatureFlags = __webpack_require__(56); var DraftModifier = __webpack_require__(23); var EditorState = __webpack_require__(15); var Keys = __webpack_require__(193); var getEntityKeyForSelection = __webpack_require__(194); var isEventHandled = __webpack_require__(104); var isSelectionAtLeafStart = __webpack_require__(446); /** * Millisecond delay to allow `compositionstart` to fire again upon * `compositionend`. * * This is used for Korean input to ensure that typing can continue without * the editor trying to render too quickly. More specifically, Safari 7.1+ * triggers `compositionstart` a little slower than Chrome/FF, which * leads to composed characters being resolved and re-render occurring * sooner than we want. */ var RESOLVE_DELAY = 20; /** * A handful of variables used to track the current composition and its * resolution status. These exist at the module level because it is not * possible to have compositions occurring in multiple editors simultaneously, * and it simplifies state management with respect to the DraftEditor component. */ var resolved = false; var stillComposing = false; var textInputData = ''; var DraftEditorCompositionHandler = { onBeforeInput: function onBeforeInput(editor, e) { textInputData = (textInputData || '') + e.data; }, /** * A `compositionstart` event has fired while we're still in composition * mode. Continue the current composition session to prevent a re-render. */ onCompositionStart: function onCompositionStart(editor) { stillComposing = true; }, /** * Attempt to end the current composition session. * * Defer handling because browser will still insert the chars into active * element after `compositionend`. If a `compositionstart` event fires * before `resolveComposition` executes, our composition session will * continue. * * The `resolved` flag is useful because certain IME interfaces fire the * `compositionend` event multiple times, thus queueing up multiple attempts * at handling the composition. Since handling the same composition event * twice could break the DOM, we only use the first event. Example: Arabic * Google Input Tools on Windows 8.1 fires `compositionend` three times. */ onCompositionEnd: function onCompositionEnd(editor) { resolved = false; stillComposing = false; setTimeout(function () { if (!resolved) { DraftEditorCompositionHandler.resolveComposition(editor); } }, RESOLVE_DELAY); }, /** * In Safari, keydown events may fire when committing compositions. If * the arrow keys are used to commit, prevent default so that the cursor * doesn't move, otherwise it will jump back noticeably on re-render. */ onKeyDown: function onKeyDown(editor, e) { if (!stillComposing) { // If a keydown event is received after compositionend but before the // 20ms timer expires (ex: type option-E then backspace, or type A then // backspace in 2-Set Korean), we should immediately resolve the // composition and reinterpret the key press in edit mode. DraftEditorCompositionHandler.resolveComposition(editor); editor._onKeyDown(e); return; } if (e.which === Keys.RIGHT || e.which === Keys.LEFT) { e.preventDefault(); } }, /** * Keypress events may fire when committing compositions. In Firefox, * pressing RETURN commits the composition and inserts extra newline * characters that we do not want. `preventDefault` allows the composition * to be committed while preventing the extra characters. */ onKeyPress: function onKeyPress(editor, e) { if (e.which === Keys.RETURN) { e.preventDefault(); } }, /** * Attempt to insert composed characters into the document. * * If we are still in a composition session, do nothing. Otherwise, insert * the characters into the document and terminate the composition session. * * If no characters were composed -- for instance, the user * deleted all composed characters and committed nothing new -- * force a re-render. We also re-render when the composition occurs * at the beginning of a leaf, to ensure that if the browser has * created a new text node for the composition, we will discard it. * * Resetting innerHTML will move focus to the beginning of the editor, * so we update to force it back to the correct place. */ resolveComposition: function resolveComposition(editor) { if (stillComposing) { return; } resolved = true; var composedChars = textInputData; textInputData = ''; var editorState = EditorState.set(editor._latestEditorState, { inCompositionMode: false }); var currentStyle = editorState.getCurrentInlineStyle(); var entityKey = getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()); var mustReset = !composedChars || isSelectionAtLeafStart(editorState) || currentStyle.size > 0 || entityKey !== null; if (mustReset) { editor.restoreEditorDOM(); } editor.exitCurrentMode(); if (composedChars) { if (DraftFeatureFlags.draft_handlebeforeinput_composed_text && editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(composedChars, editorState))) { return; } // If characters have been composed, re-rendering with the update // is sufficient to reset the editor. var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), composedChars, currentStyle, entityKey); editor.update(EditorState.push(editorState, contentState, 'insert-characters')); return; } if (mustReset) { editor.update(EditorState.set(editorState, { nativelyRenderedContent: null, forceSelection: true })); } } }; module.exports = DraftEditorCompositionHandler; /***/ }), /* 964 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorContents.react * @format * */ var DraftEditorContents = __webpack_require__(965); module.exports = DraftEditorContents; /***/ }), /* 965 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorContents-core.react * @format * */ var _assign = __webpack_require__(18); var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DraftEditorBlock = __webpack_require__(447); var DraftOffsetKey = __webpack_require__(128); var EditorState = __webpack_require__(15); var React = __webpack_require__(0); var cx = __webpack_require__(85); var joinClasses = __webpack_require__(986); var nullthrows = __webpack_require__(35); /** * Provide default styling for list items. This way, lists will be styled with * proper counters and indentation even if the caller does not specify * their own styling at all. If more than five levels of nesting are needed, * the necessary CSS classes can be provided via `blockStyleFn` configuration. */ var getListItemClasses = function getListItemClasses(type, depth, shouldResetCount, direction) { return cx({ 'public/DraftStyleDefault/unorderedListItem': type === 'unordered-list-item', 'public/DraftStyleDefault/orderedListItem': type === 'ordered-list-item', 'public/DraftStyleDefault/reset': shouldResetCount, 'public/DraftStyleDefault/depth0': depth === 0, 'public/DraftStyleDefault/depth1': depth === 1, 'public/DraftStyleDefault/depth2': depth === 2, 'public/DraftStyleDefault/depth3': depth === 3, 'public/DraftStyleDefault/depth4': depth === 4, 'public/DraftStyleDefault/listLTR': direction === 'LTR', 'public/DraftStyleDefault/listRTL': direction === 'RTL' }); }; /** * `DraftEditorContents` is the container component for all block components * rendered for a `DraftEditor`. It is optimized to aggressively avoid * re-rendering blocks whenever possible. * * This component is separate from `DraftEditor` because certain props * (for instance, ARIA props) must be allowed to update without affecting * the contents of the editor. */ var DraftEditorContents = function (_React$Component) { _inherits(DraftEditorContents, _React$Component); function DraftEditorContents() { _classCallCheck(this, DraftEditorContents); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DraftEditorContents.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { var prevEditorState = this.props.editorState; var nextEditorState = nextProps.editorState; var prevDirectionMap = prevEditorState.getDirectionMap(); var nextDirectionMap = nextEditorState.getDirectionMap(); // Text direction has changed for one or more blocks. We must re-render. if (prevDirectionMap !== nextDirectionMap) { return true; } var didHaveFocus = prevEditorState.getSelection().getHasFocus(); var nowHasFocus = nextEditorState.getSelection().getHasFocus(); if (didHaveFocus !== nowHasFocus) { return true; } var nextNativeContent = nextEditorState.getNativelyRenderedContent(); var wasComposing = prevEditorState.isInCompositionMode(); var nowComposing = nextEditorState.isInCompositionMode(); // If the state is unchanged or we're currently rendering a natively // rendered state, there's nothing new to be done. if (prevEditorState === nextEditorState || nextNativeContent !== null && nextEditorState.getCurrentContent() === nextNativeContent || wasComposing && nowComposing) { return false; } var prevContent = prevEditorState.getCurrentContent(); var nextContent = nextEditorState.getCurrentContent(); var prevDecorator = prevEditorState.getDecorator(); var nextDecorator = nextEditorState.getDecorator(); return wasComposing !== nowComposing || prevContent !== nextContent || prevDecorator !== nextDecorator || nextEditorState.mustForceSelection(); }; DraftEditorContents.prototype.render = function render() { var _props = this.props, blockRenderMap = _props.blockRenderMap, blockRendererFn = _props.blockRendererFn, blockStyleFn = _props.blockStyleFn, customStyleMap = _props.customStyleMap, customStyleFn = _props.customStyleFn, editorState = _props.editorState, editorKey = _props.editorKey, textDirectionality = _props.textDirectionality; var content = editorState.getCurrentContent(); var selection = editorState.getSelection(); var forceSelection = editorState.mustForceSelection(); var decorator = editorState.getDecorator(); var directionMap = nullthrows(editorState.getDirectionMap()); var blocksAsArray = content.getBlocksAsArray(); var processedBlocks = []; var currentDepth = null; var lastWrapperTemplate = null; for (var ii = 0; ii < blocksAsArray.length; ii++) { var _block = blocksAsArray[ii]; var key = _block.getKey(); var blockType = _block.getType(); var customRenderer = blockRendererFn(_block); var CustomComponent = void 0, customProps = void 0, customEditable = void 0; if (customRenderer) { CustomComponent = customRenderer.component; customProps = customRenderer.props; customEditable = customRenderer.editable; } var direction = textDirectionality ? textDirectionality : directionMap.get(key); var offsetKey = DraftOffsetKey.encode(key, 0, 0); var componentProps = { contentState: content, block: _block, blockProps: customProps, blockStyleFn: blockStyleFn, customStyleMap: customStyleMap, customStyleFn: customStyleFn, decorator: decorator, direction: direction, forceSelection: forceSelection, key: key, offsetKey: offsetKey, selection: selection, tree: editorState.getBlockTree(key) }; var configForType = blockRenderMap.get(blockType) || blockRenderMap.get('unstyled'); var wrapperTemplate = configForType.wrapper; var Element = configForType.element || blockRenderMap.get('unstyled').element; var depth = _block.getDepth(); var className = ''; if (blockStyleFn) { className = blockStyleFn(_block); } // List items are special snowflakes, since we handle nesting and // counters manually. if (Element === 'li') { var shouldResetCount = lastWrapperTemplate !== wrapperTemplate || currentDepth === null || depth > currentDepth; className = joinClasses(className, getListItemClasses(blockType, depth, shouldResetCount, direction)); } var Component = CustomComponent || DraftEditorBlock; var childProps = { className: className, 'data-block': true, 'data-editor': editorKey, 'data-offset-key': offsetKey, key: key }; if (customEditable !== undefined) { childProps = _extends({}, childProps, { contentEditable: customEditable, suppressContentEditableWarning: true }); } var child = React.createElement(Element, childProps, React.createElement(Component, componentProps)); processedBlocks.push({ block: child, wrapperTemplate: wrapperTemplate, key: key, offsetKey: offsetKey }); if (wrapperTemplate) { currentDepth = _block.getDepth(); } else { currentDepth = null; } lastWrapperTemplate = wrapperTemplate; } // Group contiguous runs of blocks that have the same wrapperTemplate var outputBlocks = []; for (var _ii = 0; _ii < processedBlocks.length;) { var info = processedBlocks[_ii]; if (info.wrapperTemplate) { var blocks = []; do { blocks.push(processedBlocks[_ii].block); _ii++; } while (_ii < processedBlocks.length && processedBlocks[_ii].wrapperTemplate === info.wrapperTemplate); var wrapperElement = React.cloneElement(info.wrapperTemplate, { key: info.key + '-wrap', 'data-offset-key': info.offsetKey }, blocks); outputBlocks.push(wrapperElement); } else { outputBlocks.push(info.block); _ii++; } } return React.createElement( 'div', { 'data-contents': 'true' }, outputBlocks ); }; return DraftEditorContents; }(React.Component); module.exports = DraftEditorContents; /***/ }), /* 966 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorLeaf.react * @format * */ var _assign = __webpack_require__(18); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DraftEditorTextNode = __webpack_require__(967); var React = __webpack_require__(0); var ReactDOM = __webpack_require__(8); var invariant = __webpack_require__(10); var setDraftEditorSelection = __webpack_require__(974); /** * All leaf nodes in the editor are spans with single text nodes. Leaf * elements are styled based on the merging of an optional custom style map * and a default style map. * * `DraftEditorLeaf` also provides a wrapper for calling into the imperative * DOM Selection API. In this way, top-level components can declaratively * maintain the selection state. */ var DraftEditorLeaf = function (_React$Component) { _inherits(DraftEditorLeaf, _React$Component); function DraftEditorLeaf() { _classCallCheck(this, DraftEditorLeaf); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } DraftEditorLeaf.prototype._setSelection = function _setSelection() { var selection = this.props.selection; // If selection state is irrelevant to the parent block, no-op. if (selection == null || !selection.getHasFocus()) { return; } var _props = this.props, block = _props.block, start = _props.start, text = _props.text; var blockKey = block.getKey(); var end = start + text.length; if (!selection.hasEdgeWithin(blockKey, start, end)) { return; } // Determine the appropriate target node for selection. If the child // is not a text node, it is a
spacer. In this case, use the // itself as the selection target. var node = ReactDOM.findDOMNode(this); !node ? true ? invariant(false, 'Missing node') : invariant(false) : void 0; var child = node.firstChild; !child ? true ? invariant(false, 'Missing child') : invariant(false) : void 0; var targetNode = void 0; if (child.nodeType === Node.TEXT_NODE) { targetNode = child; } else if (child.tagName === 'BR') { targetNode = node; } else { targetNode = child.firstChild; !targetNode ? true ? invariant(false, 'Missing targetNode') : invariant(false) : void 0; } setDraftEditorSelection(selection, targetNode, blockKey, start, end); }; /** * By making individual leaf instances aware of their context within * the text of the editor, we can set our selection range more * easily than we could in the non-React world. * * Note that this depends on our maintaining tight control over the * DOM structure of the DraftEditor component. If leaves had multiple * text nodes, this would be harder. */ DraftEditorLeaf.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { var leafNode = ReactDOM.findDOMNode(this.leaf); !leafNode ? true ? invariant(false, 'Missing leafNode') : invariant(false) : void 0; return leafNode.textContent !== nextProps.text || nextProps.styleSet !== this.props.styleSet || nextProps.forceSelection; }; DraftEditorLeaf.prototype.componentDidUpdate = function componentDidUpdate() { this._setSelection(); }; DraftEditorLeaf.prototype.componentDidMount = function componentDidMount() { this._setSelection(); }; DraftEditorLeaf.prototype.render = function render() { var _this2 = this; var block = this.props.block; var text = this.props.text; // If the leaf is at the end of its block and ends in a soft newline, append // an extra line feed character. Browsers collapse trailing newline // characters, which leaves the cursor in the wrong place after a // shift+enter. The extra character repairs this. if (text.endsWith('\n') && this.props.isLast) { text += '\n'; } var _props2 = this.props, customStyleMap = _props2.customStyleMap, customStyleFn = _props2.customStyleFn, offsetKey = _props2.offsetKey, styleSet = _props2.styleSet; var styleObj = styleSet.reduce(function (map, styleName) { var mergedStyles = {}; var style = customStyleMap[styleName]; if (style !== undefined && map.textDecoration !== style.textDecoration) { // .trim() is necessary for IE9/10/11 and Edge mergedStyles.textDecoration = [map.textDecoration, style.textDecoration].join(' ').trim(); } return _assign(map, style, mergedStyles); }, {}); if (customStyleFn) { var newStyles = customStyleFn(styleSet, block); styleObj = _assign(styleObj, newStyles); } return React.createElement( 'span', { 'data-offset-key': offsetKey, ref: function ref(_ref) { return _this2.leaf = _ref; }, style: styleObj }, React.createElement( DraftEditorTextNode, null, text ) ); }; return DraftEditorLeaf; }(React.Component); module.exports = DraftEditorLeaf; /***/ }), /* 967 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorTextNode.react * @format * */ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = __webpack_require__(0); var ReactDOM = __webpack_require__(8); var UserAgent = __webpack_require__(44); var invariant = __webpack_require__(10); // In IE, spans with
tags render as two newlines. By rendering a span // with only a newline character, we can be sure to render a single line. var useNewlineChar = UserAgent.isBrowser('IE <= 11'); /** * Check whether the node should be considered a newline. */ function isNewline(node) { return useNewlineChar ? node.textContent === '\n' : node.tagName === 'BR'; } /** * Placeholder elements for empty text content. * * What is this `data-text` attribute, anyway? It turns out that we need to * put an attribute on the lowest-level text node in order to preserve correct * spellcheck handling. If the is naked, Chrome and Safari may do * bizarre things to do the DOM -- split text nodes, create extra spans, etc. * If the has an attribute, this appears not to happen. * See http://jsfiddle.net/9khdavod/ for the failure case, and * http://jsfiddle.net/7pg143f7/ for the fixed case. */ var NEWLINE_A = useNewlineChar ? React.createElement( 'span', { key: 'A', 'data-text': 'true' }, '\n' ) : React.createElement('br', { key: 'A', 'data-text': 'true' }); var NEWLINE_B = useNewlineChar ? React.createElement( 'span', { key: 'B', 'data-text': 'true' }, '\n' ) : React.createElement('br', { key: 'B', 'data-text': 'true' }); /** * The lowest-level component in a `DraftEditor`, the text node component * replaces the default React text node implementation. This allows us to * perform custom handling of newline behavior and avoid re-rendering text * nodes with DOM state that already matches the expectations of our immutable * editor state. */ var DraftEditorTextNode = function (_React$Component) { _inherits(DraftEditorTextNode, _React$Component); function DraftEditorTextNode(props) { _classCallCheck(this, DraftEditorTextNode); // By flipping this flag, we also keep flipping keys which forces // React to remount this node every time it rerenders. var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this._forceFlag = false; return _this; } DraftEditorTextNode.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { var node = ReactDOM.findDOMNode(this); var shouldBeNewline = nextProps.children === ''; !(node instanceof Element) ? true ? invariant(false, 'node is not an Element') : invariant(false) : void 0; if (shouldBeNewline) { return !isNewline(node); } return node.textContent !== nextProps.children; }; DraftEditorTextNode.prototype.componentDidMount = function componentDidMount() { this._forceFlag = !this._forceFlag; }; DraftEditorTextNode.prototype.componentDidUpdate = function componentDidUpdate() { this._forceFlag = !this._forceFlag; }; DraftEditorTextNode.prototype.render = function render() { if (this.props.children === '') { return this._forceFlag ? NEWLINE_A : NEWLINE_B; } return React.createElement( 'span', { key: this._forceFlag ? 'A' : 'B', 'data-text': 'true' }, this.props.children ); }; return DraftEditorTextNode; }(React.Component); module.exports = DraftEditorTextNode; /***/ }), /* 968 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ /** * Usage note: * This module makes a best effort to export the same data we would internally. * At Facebook we use a server-generated module that does the parsing and * exports the data for the client to use. We can't rely on a server-side * implementation in open source so instead we make use of an open source * library to do the heavy lifting and then make some adjustments as necessary. * It's likely there will be some differences. Some we can smooth over. * Others are going to be harder. */ var UAParser = __webpack_require__(969); var UNKNOWN = 'Unknown'; var PLATFORM_MAP = { 'Mac OS': 'Mac OS X' }; /** * Convert from UAParser platform name to what we expect. */ function convertPlatformName(name) { return PLATFORM_MAP[name] || name; } /** * Get the version number in parts. This is very naive. We actually get major * version as a part of UAParser already, which is generally good enough, but * let's get the minor just in case. */ function getBrowserVersion(version) { if (!version) { return { major: '', minor: '' }; } var parts = version.split('.'); return { major: parts[0], minor: parts[1] }; } /** * Get the UA data fom UAParser and then convert it to the format we're * expecting for our APIS. */ var parser = new UAParser(); var results = parser.getResult(); // Do some conversion first. var browserVersionData = getBrowserVersion(results.browser.version); var uaData = { browserArchitecture: results.cpu.architecture || UNKNOWN, browserFullVersion: results.browser.version || UNKNOWN, browserMinorVersion: browserVersionData.minor || UNKNOWN, browserName: results.browser.name || UNKNOWN, browserVersion: results.browser.major || UNKNOWN, deviceName: results.device.model || UNKNOWN, engineName: results.engine.name || UNKNOWN, engineVersion: results.engine.version || UNKNOWN, platformArchitecture: results.cpu.architecture || UNKNOWN, platformName: convertPlatformName(results.os.name) || UNKNOWN, platformVersion: results.os.version || UNKNOWN, platformFullVersion: results.os.version || UNKNOWN }; module.exports = uaData; /***/ }), /* 969 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * UAParser.js v0.7.19 * Lightweight JavaScript-based User-Agent string parser * https://github.com/faisalman/ua-parser-js * * Copyright © 2012-2016 Faisal Salman * Dual licensed under GPLv2 or MIT */ (function (window, undefined) { 'use strict'; ////////////// // Constants ///////////// var LIBVERSION = '0.7.19', EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', STR_TYPE = 'string', MAJOR = 'major', // deprecated MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE= 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet', SMARTTV = 'smarttv', WEARABLE = 'wearable', EMBEDDED = 'embedded'; /////////// // Helper ////////// var util = { extend : function (regexes, extensions) { var margedRegexes = {}; for (var i in regexes) { if (extensions[i] && extensions[i].length % 2 === 0) { margedRegexes[i] = extensions[i].concat(regexes[i]); } else { margedRegexes[i] = regexes[i]; } } return margedRegexes; }, has : function (str1, str2) { if (typeof str1 === "string") { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; } else { return false; } }, lowerize : function (str) { return str.toLowerCase(); }, major : function (version) { return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g,'').split(".")[0] : undefined; }, trim : function (str) { return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } }; /////////////// // Map helper ////////////// var mapper = { rgx : function (ua, arrays) { //var result = {}, var i = 0, j, k, p, q, matches, match;//, args = arguments; /*// construct object barebones for (p = 0; p < args[1].length; p++) { q = args[1][p]; result[typeof q === OBJ_TYPE ? q[0] : q] = undefined; }*/ // loop through all regexes maps while (i < arrays.length && !matches) { var regex = arrays[i], // even sequence (0,2,4,..) props = arrays[i + 1]; // odd sequence (1,3,5,..) j = k = 0; // try matching uastring with regexes while (j < regex.length && !matches) { matches = regex[j++].exec(ua); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof q === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (typeof q[1] == FUNC_TYPE) { // assign modified match this[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match this[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex this[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { this[q] = match ? match : undefined; } } } } i += 2; } // console.log(this); //return this; }, str : function (str, map) { for (var i in map) { // check if array if (typeof map[i] === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], str)) { return (i === UNKNOWN) ? undefined : i; } } } else if (util.has(map[i], str)) { return (i === UNKNOWN) ? undefined : i; } } return str; } }; /////////////// // String map ////////////// var maps = { browser : { oldsafari : { version : { '1.0' : '/8', '1.2' : '/1', '1.3' : '/3', '2.0' : '/412', '2.0.2' : '/416', '2.0.3' : '/417', '2.0.4' : '/419', '?' : '/' } } }, device : { amazon : { model : { 'Fire Phone' : ['SD', 'KF'] } }, sprint : { model : { 'Evo Shift 4G' : '7373KT' }, vendor : { 'HTC' : 'APA', 'Sprint' : 'Sprint' } } }, os : { windows : { version : { 'ME' : '4.90', 'NT 3.11' : 'NT3.51', 'NT 4.0' : 'NT4.0', '2000' : 'NT 5.0', 'XP' : ['NT 5.1', 'NT 5.2'], 'Vista' : 'NT 6.0', '7' : 'NT 6.1', '8' : 'NT 6.2', '8.1' : 'NT 6.3', '10' : ['NT 6.4', 'NT 10.0'], 'RT' : 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser : [[ // Presto based /(opera\smini)\/([\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/([\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION], [ /(opios)[\/\s]+([\w\.]+)/i // Opera mini on iphone >= 8.0 ], [[NAME, 'Opera Mini'], VERSION], [ /\s(opr)\/([\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION], [ // Mixed /(kindle)\/([\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]*)/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)\/([\w\.]*)/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark)\/([\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser ], [NAME, VERSION], [ /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION], [ /(edge|edgios|edga)\/((\d+)?[\w\.]+)/i // Microsoft Edge ], [[NAME, 'Edge'], VERSION], [ /(yabrowser)\/([\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION], [ /(puffin)\/([\w\.]+)/i // Puffin ], [[NAME, 'Puffin'], VERSION], [ /(focus)\/([\w\.]+)/i // Firefox Focus ], [[NAME, 'Firefox Focus'], VERSION], [ /(opt)\/([\w\.]+)/i // Opera Touch ], [[NAME, 'Opera Touch'], VERSION], [ /((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i // UCBrowser ], [[NAME, 'UCBrowser'], VERSION], [ /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION], [ /(micromessenger)\/([\w\.]+)/i // WeChat ], [[NAME, 'WeChat'], VERSION], [ /(brave)\/([\w\.]+)/i // Brave browser ], [[NAME, 'Brave'], VERSION], [ /(qqbrowserlite)\/([\w\.]+)/i // QQBrowserLite ], [NAME, VERSION], [ /(QQ)\/([\d\.]+)/i // QQ, aka ShouQ ], [NAME, VERSION], [ /m?(qqbrowser)[\/\s]?([\w\.]+)/i // QQBrowser ], [NAME, VERSION], [ /(BIDUBrowser)[\/\s]?([\w\.]+)/i // Baidu Browser ], [NAME, VERSION], [ /(2345Explorer)[\/\s]?([\w\.]+)/i // 2345 Browser ], [NAME, VERSION], [ /(MetaSr)[\/\s]?([\w\.]+)/i // SouGouBrowser ], [NAME], [ /(LBBROWSER)/i // LieBao Browser ], [NAME], [ /xiaomi\/miuibrowser\/([\w\.]+)/i // MIUI Browser ], [VERSION, [NAME, 'MIUI Browser']], [ /;fbav\/([\w\.]+);/i // Facebook App for iOS & Android ], [VERSION, [NAME, 'Facebook']], [ /safari\s(line)\/([\w\.]+)/i, // Line App for iOS /android.+(line)\/([\w\.]+)\/iab/i // Line App for Android ], [NAME, VERSION], [ /headlesschrome(?:\/([\w\.]+)|\s)/i // Chrome Headless ], [VERSION, [NAME, 'Chrome Headless']], [ /\swv\).+(chrome)\/([\w\.]+)/i // Chrome WebView ], [[NAME, /(.+)/, '$1 WebView'], VERSION], [ /((?:oculus|samsung)browser)\/([\w\.]+)/i ], [[NAME, /(.+(?:g|us))(.+)/, '$1 $2'], VERSION], [ // Oculus / Samsung Browser /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i // Android Browser ], [VERSION, [NAME, 'Android Browser']], [ /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION], [ /(dolfin)\/([\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION], [ /((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION], [ /(coast)\/([\w\.]+)/i // Opera Coast ], [[NAME, 'Opera Coast'], VERSION], [ /fxios\/([\w\.-]+)/i // Firefox for iOS ], [VERSION, [NAME, 'Firefox']], [ /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, [NAME, 'Mobile Safari']], [ /version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, NAME], [ /webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Google Search Appliance on iOS ], [[NAME, 'GSA'], VERSION], [ /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0 ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [ /(konqueror)\/([\w\.]+)/i, // Konqueror /(webkit|khtml)\/([\w\.]+)/i ], [NAME, VERSION], [ // Gecko based /(navigator|netscape)\/([\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION], [ /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([\w\.-]+)$/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i, // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir /(links)\s\(([\w\.]+)/i, // Links /(gobrowser)\/?([\w\.]*)/i, // GoBrowser /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]([\w\.]+)/i // Mosaic ], [NAME, VERSION] /* ///////////////////// // Media players BEGIN //////////////////////// , [ /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i, // Generic Apple CoreMedia /(coremedia) v((\d+)[\w\._]+)/i ], [NAME, VERSION], [ /(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i // Aqualung/Lyssna/BSPlayer ], [NAME, VERSION], [ /(ares|ossproxy)\s((\d+)[\w\.-]+)/i // Ares/OSSProxy ], [NAME, VERSION], [ /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i, // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC // NSPlayer/PSP-InternetRadioPlayer/Videos /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i, // Clementine/MPD /(lg player|nexplayer)\s((\d+)[\d\.]+)/i, /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i // NexPlayer/LG Player ], [NAME, VERSION], [ /(nexplayer)\s((\d+)[\w\.-]+)/i // Nexplayer ], [NAME, VERSION], [ /(flrp)\/((\d+)[\w\.-]+)/i // Flip Player ], [[NAME, 'Flip Player'], VERSION], [ /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit ], [NAME], [ /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i // Gstreamer ], [NAME, VERSION], [ /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i, // HTC Streaming Player /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i, // Java/urllib/requests/wget/cURL /(lavf)((\d+)[\d\.]+)/i // Lavf (FFMPEG) ], [NAME, VERSION], [ /(htc_one_s)\/((\d+)[\d\.]+)/i // HTC One S ], [[NAME, /_/g, ' '], VERSION], [ /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i // MPlayer SVN ], [NAME, VERSION], [ /(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i // MPlayer ], [NAME, VERSION], [ /(mplayer)/i, // MPlayer (no other info) /(yourmuze)/i, // YourMuze /(media player classic|nero showtime)/i // Media Player Classic/Nero ShowTime ], [NAME], [ /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i // Nero Home/Nero Scout ], [NAME, VERSION], [ /(nokia\d+)\/((\d+)[\w\.-]+)/i // Nokia ], [NAME, VERSION], [ /\s(songbird)\/((\d+)[\w\.-]+)/i // Songbird/Philips-Songbird ], [NAME, VERSION], [ /(winamp)3 version ((\d+)[\w\.-]+)/i, // Winamp /(winamp)\s((\d+)[\w\.-]+)/i, /(winamp)mpeg\/((\d+)[\w\.-]+)/i ], [NAME, VERSION], [ /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info) // inlight radio ], [NAME], [ /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i // QuickTime/RealMedia/RadioApp/RadioClientApplication/ // SoundTap/Totem/Stagefright/Streamium ], [NAME, VERSION], [ /(smp)((\d+)[\d\.]+)/i // SMP ], [NAME, VERSION], [ /(vlc) media player - version ((\d+)[\w\.]+)/i, // VLC Videolan /(vlc)\/((\d+)[\w\.-]+)/i, /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i, // XBMC/gvfs/Xine/XMMS/irapp /(foobar2000)\/((\d+)[\d\.]+)/i, // Foobar2000 /(itunes)\/((\d+)[\d\.]+)/i // iTunes ], [NAME, VERSION], [ /(wmplayer)\/((\d+)[\w\.-]+)/i, // Windows Media Player /(windows-media-player)\/((\d+)[\w\.-]+)/i ], [[NAME, /-/g, ' '], VERSION], [ /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i // Windows Media Server ], [VERSION, [NAME, 'Windows']], [ /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i // RiseUP Radio Alarm ], [NAME, VERSION], [ /(rad.io)\s((\d+)[\d\.]+)/i, // Rad.io /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i ], [[NAME, 'rad.io'], VERSION] ////////////////////// // Media players END ////////////////////*/ ], cpu : [[ /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64 ], [[ARCHITECTURE, 'amd64']], [ /(ia32(?=;))/i // IA32 (quicktime) ], [[ARCHITECTURE, util.lowerize]], [ /((?:i[346]|x)86)[;\)]/i // IA32 ], [[ARCHITECTURE, 'ia32']], [ // PocketPC mistakenly identified as PowerPC /windows\s(ce|mobile);\sppc;/i ], [[ARCHITECTURE, 'arm']], [ /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [ /(sun4\w)[;\)]/i // SPARC ], [[ARCHITECTURE, 'sparc']], [ /((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+[;l]))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC ], [[ARCHITECTURE, util.lowerize]] ], device : [[ /\((ipad|playbook);[\w\s\);-]+(rim|apple)/i // iPad/PlayBook ], [MODEL, VENDOR, [TYPE, TABLET]], [ /applecoremedia\/[\w\.]+ \((ipad)/ // iPad ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [ /(apple\s{0,1}tv)/i // Apple TV ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [ /(archos)\s(gamepad2?)/i, // Archos /(hp).+(touchpad)/i, // HP TouchPad /(hp).+(tablet)/i, // HP Tablet /(kindle)\/([\w\.]+)/i, // Kindle /\s(nook)[\w\s]+build\/(\w+)/i, // Nook /(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak ], [VENDOR, MODEL, [TYPE, TABLET]], [ /(kf[A-z]+)\sbuild\/.+silk\//i // Kindle Fire HD ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [ /(sd|kf)[0349hijorstuw]+\sbuild\/.+silk\//i // Fire Phone ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [ /android.+aft([bms])\sbuild/i // Fire TV ], [MODEL, [VENDOR, 'Amazon'], [TYPE, SMARTTV]], [ /\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone ], [MODEL, VENDOR, [TYPE, MOBILE]], [ /\((ip[honed|\s\w*]+);/i // iPod/iPhone ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [ /(blackberry)[\s-]?(\w+)/i, // BlackBerry /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]*)/i, // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron /(hp)\s([\w\s]+\w)/i, // HP iPAQ /(asus)-?(\w+)/i // Asus ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /\(bb10;\s(\w+)/i // BlackBerry 10 ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [ // Asus Tablets /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i ], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [ /(sony)\s(tablet\s[ps])\sbuild\//i, // Sony /(sony)?(?:sgp.+)\sbuild\//i ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [ /android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i ], [MODEL, [VENDOR, 'Sony'], [TYPE, MOBILE]], [ /\s(ouya)\s/i, // Ouya /(nintendo)\s([wids3u]+)/i // Nintendo ], [VENDOR, MODEL, [TYPE, CONSOLE]], [ /android.+;\s(shield)\sbuild/i // Nvidia ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [ /(playstation\s[34portablevi]+)/i // Playstation ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [ /(sprint\s(\w+))/i // Sprint Phones ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [ /(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i // Lenovo tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [ /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i, // HTC /(zte)-(\w*)/i, // ZTE /(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]*)/i // Alcatel/GeeksPhone/Lenovo/Nexian/Panasonic/Sony ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [ /(nexus\s9)/i // HTC Nexus 9 ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [ /d\/huawei([\w\s-]+)[;\)]/i, /(nexus\s6p)/i // Huawei ], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [ /(microsoft);\s(lumia[\s\w]+)/i // Microsoft Lumia ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /[\s\(;](xbox(?:\sone)?)[\s\);]/i // Microsoft Xbox ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [ /(kin\.[onetw]{3})/i // Microsoft Kin ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [ // Motorola /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?:?(\s4g)?)[\w\s]+build\//i, /mot[\s-]?(\w*)/i, /(XT\d{3,4}) build\//i, /(nexus\s6)/i ], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [ /android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i ], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [ /hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i // HbbTV devices ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [ /hbbtv.+maple;(\d+)/i ], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [ /\(dtv[\);].+(aquos)/i // Sharp ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [ /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i, /((SM-T\w+))/i ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [ // Samsung /smart-tv.+(samsung)/i ], [VENDOR, [TYPE, SMARTTV], MODEL], [ /((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i, /(sam[sung]*)[\s-]*(\w+-?[\w-]*)/i, /sec-((sgh\w+))/i ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [ /sie-(\w*)/i // Siemens ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [ /(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia /(nokia)[\s_-]?([\w-]*)/i ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [ /android\s3\.[\s\w;-]{10}(a\d{3})/i // Acer ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [ /android.+([vl]k\-?\d{3})\s+build/i // LG Tablet ], [MODEL, [VENDOR, 'LG'], [TYPE, TABLET]], [ /android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i // LG Tablet ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [ /(lg) netcast\.tv/i // LG SmartTV ], [VENDOR, MODEL, [TYPE, SMARTTV]], [ /(nexus\s[45])/i, // LG /lg[e;\s\/-]+(\w*)/i, /android.+lg(\-?[\d\w]+)\s+build/i ], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [ /android.+(ideatab[a-z0-9\-\s]+)/i // Lenovo ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [ /linux;.+((jolla));/i // Jolla ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /((pebble))app\/[\d\.]+\s/i // Pebble ], [VENDOR, MODEL, [TYPE, WEARABLE]], [ /android.+;\s(oppo)\s?([\w\s]+)\sbuild/i // OPPO ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /crkey/i // Google Chromecast ], [[MODEL, 'Chromecast'], [VENDOR, 'Google']], [ /android.+;\s(glass)\s\d/i // Google Glass ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [ /android.+;\s(pixel c)[\s)]/i // Google Pixel C ], [MODEL, [VENDOR, 'Google'], [TYPE, TABLET]], [ /android.+;\s(pixel( [23])?( xl)?)\s/i // Google Pixel ], [MODEL, [VENDOR, 'Google'], [TYPE, MOBILE]], [ /android.+;\s(\w+)\s+build\/hm\1/i, // Xiaomi Hongmi 'numeric' models /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Hongmi /android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d?\w?)[\s_]*(?:plus)?)\s+build/i, // Xiaomi Mi /android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+))\s+build/i // Redmi Phones ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [ /android.+(mi[\s\-_]*(?:pad)(?:[\s_]*[\w\s]+))\s+build/i // Mi Pad tablets ],[[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, TABLET]], [ /android.+;\s(m[1-5]\snote)\sbuild/i // Meizu Tablet ], [MODEL, [VENDOR, 'Meizu'], [TYPE, TABLET]], [ /(mz)-([\w-]{2,})/i // Meizu Phone ], [[VENDOR, 'Meizu'], MODEL, [TYPE, MOBILE]], [ /android.+a000(1)\s+build/i, // OnePlus /android.+oneplus\s(a\d{4})\s+build/i ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [ /android.+[;\/]\s*(RCT[\d\w]+)\s+build/i // RCA Tablets ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [ /android.+[;\/\s]+(Venue[\d\s]{2,7})\s+build/i // Dell Venue Tablets ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [ /android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i // Verizon Tablet ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [ /android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i // Barnes & Noble Tablet ], [[VENDOR, 'Barnes & Noble'], MODEL, [TYPE, TABLET]], [ /android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i // Barnes & Noble Tablet ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [ /android.+;\s(k88)\sbuild/i // ZTE K Series Tablet ], [MODEL, [VENDOR, 'ZTE'], [TYPE, TABLET]], [ /android.+[;\/]\s*(gen\d{3})\s+build.*49h/i // Swiss GEN Mobile ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [ /android.+[;\/]\s*(zur\d{3})\s+build/i // Swiss ZUR Tablet ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [ /android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i // Zeki Tablets ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [ /(android).+[;\/]\s+([YR]\d{2})\s+build/i, /android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(\w{5})\sbuild/i // Dragon Touch Tablet ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [ /android.+[;\/]\s*(NS-?\w{0,9})\sbuild/i // Insignia Tablets ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [ /android.+[;\/]\s*((NX|Next)-?\w{0,9})\s+build/i // NextBook Tablets ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [ /android.+[;\/]\s*(Xtreme\_)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [ // Voice Xtreme Phones /android.+[;\/]\s*(LVTEL\-)?(V1[12])\s+build/i // LvTel Phones ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [ /android.+;\s(PH-1)\s/i ], [MODEL, [VENDOR, 'Essential'], [TYPE, MOBILE]], [ // Essential PH-1 /android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i // Envizen Tablets ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [ /android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(\w{1,9})\s+build/i // Le Pan Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [ /android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i // MachSpeed Tablets ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [ /android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i // Trinity Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [ /android.+[;\/]\s*TU_(1491)\s+build/i // Rotor Tablets ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [ /android.+(KS(.+))\s+build/i // Amazon Kindle Tablets ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [ /android.+(Gigaset)[\s\-]+(Q\w{1,9})\s+build/i // Gigaset Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [ /\s(tablet|tab)[;\/]/i, // Unidentifiable Tablet /\s(mobile)(?:[;\/]|\ssafari)/i // Unidentifiable Mobile ], [[TYPE, util.lowerize], VENDOR, MODEL], [ /(android[\w\.\s\-]{0,9});.+build/i // Generic Android Device ], [MODEL, [VENDOR, 'Generic']] /*////////////////////////// // TODO: move to string map //////////////////////////// /(C6603)/i // Sony Xperia Z C6603 ], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ /(C6903)/i // Sony Xperia Z 1 ], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [ /(SM-G900[F|H])/i // Samsung Galaxy S5 ], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-G7102)/i // Samsung Galaxy Grand 2 ], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-G530H)/i // Samsung Galaxy Grand Prime ], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-G313HZ)/i // Samsung Galaxy V ], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-T805)/i // Samsung Galaxy Tab S 10.5 ], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ /(SM-G800F)/i // Samsung Galaxy S5 Mini ], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [ /(SM-T311)/i // Samsung Galaxy Tab 3 8.0 ], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [ /(T3C)/i // Advan Vandroid T3C ], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [ /(ADVAN T1J\+)/i // Advan Vandroid T1J+ ], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [ /(ADVAN S4A)/i // Advan Vandroid S4A ], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [ /(V972M)/i // ZTE V972M ], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [ /(i-mobile)\s(IQ\s[\d\.]+)/i // i-mobile IQ ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /(IQ6.3)/i // i-mobile IQ IQ 6.3 ], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ /(i-mobile)\s(i-style\s[\d\.]+)/i // i-mobile i-STYLE ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /(i-STYLE2.1)/i // i-mobile i-STYLE 2.1 ], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [ /(mobiistar touch LAI 512)/i // mobiistar touch LAI 512 ], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [ ///////////// // END TODO ///////////*/ ], engine : [[ /windows.+\sedge\/([\w\.]+)/i // EdgeHTML ], [VERSION, [NAME, 'EdgeHTML']], [ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]{1,9}).+(gecko)/i // Gecko ], [VERSION, NAME] ], os : [[ // Windows based /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes) ], [NAME, VERSION], [ /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s\w]*)/i, // Windows Phone /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [ /(blackberry)\w*\/?([\w\.]*)/i, // Blackberry /(tizen)[\/\s]([\w\.]+)/i, // Tizen /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]*)/i, // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki /linux;.+(sailfish);/i // Sailfish OS ], [NAME, VERSION], [ /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]*)/i // Symbian ], [[NAME, 'Symbian'], VERSION], [ /\((series40);/i // Series 40 ], [NAME], [ /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids34portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w*)/i, // Mint /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux /(joli|[kxln]?ubuntu|debian|suse|opensuse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]*)/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus /(hurd|linux)\s?([\w\.]*)/i, // Hurd/Linux /(gnu)\s?([\w\.]*)/i // GNU ], [NAME, VERSION], [ /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION],[ // Solaris /(sunos)\s?([\w\.\d]*)/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]*)/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION],[ /(haiku)\s(\w+)/i // Haiku ], [NAME, VERSION],[ /cfnetwork\/.+darwin/i, /ip[honead]{2,4}(?:.*os\s([\w]+)\slike\smac|;\sopera)/i // iOS ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [ /(mac\sos\sx)\s?([\w\s\.]*)/i, /(macintosh|mac(?=_powerpc)\s)/i // Mac OS ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [ // Other /((?:open)?solaris)[\/\s-]?([\w\.]*)/i, // Solaris /(aix)\s((\d)(?=\.|\)|\s)[\w\.])*/i, // AIX /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms|fuchsia)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS/Fuchsia /(unix)\s?([\w\.]*)/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// /* var Browser = function (name, version) { this[NAME] = name; this[VERSION] = version; }; var CPU = function (arch) { this[ARCHITECTURE] = arch; }; var Device = function (vendor, model, type) { this[VENDOR] = vendor; this[MODEL] = model; this[TYPE] = type; }; var Engine = Browser; var OS = Browser; */ var UAParser = function (uastring, extensions) { if (typeof uastring === 'object') { extensions = uastring; uastring = undefined; } if (!(this instanceof UAParser)) { return new UAParser(uastring, extensions).getResult(); } var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); var rgxmap = extensions ? util.extend(regexes, extensions) : regexes; //var browser = new Browser(); //var cpu = new CPU(); //var device = new Device(); //var engine = new Engine(); //var os = new OS(); this.getBrowser = function () { var browser = { name: undefined, version: undefined }; mapper.rgx.call(browser, ua, rgxmap.browser); browser.major = util.major(browser.version); // deprecated return browser; }; this.getCPU = function () { var cpu = { architecture: undefined }; mapper.rgx.call(cpu, ua, rgxmap.cpu); return cpu; }; this.getDevice = function () { var device = { vendor: undefined, model: undefined, type: undefined }; mapper.rgx.call(device, ua, rgxmap.device); return device; }; this.getEngine = function () { var engine = { name: undefined, version: undefined }; mapper.rgx.call(engine, ua, rgxmap.engine); return engine; }; this.getOS = function () { var os = { name: undefined, version: undefined }; mapper.rgx.call(os, ua, rgxmap.os); return os; }; this.getResult = function () { return { ua : this.getUA(), browser : this.getBrowser(), engine : this.getEngine(), os : this.getOS(), device : this.getDevice(), cpu : this.getCPU() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; //browser = new Browser(); //cpu = new CPU(); //device = new Device(); //engine = new Engine(); //os = new OS(); return this; }; return this; }; UAParser.VERSION = LIBVERSION; UAParser.BROWSER = { NAME : NAME, MAJOR : MAJOR, // deprecated VERSION : VERSION }; UAParser.CPU = { ARCHITECTURE : ARCHITECTURE }; UAParser.DEVICE = { MODEL : MODEL, VENDOR : VENDOR, TYPE : TYPE, CONSOLE : CONSOLE, MOBILE : MOBILE, SMARTTV : SMARTTV, TABLET : TABLET, WEARABLE: WEARABLE, EMBEDDED: EMBEDDED }; UAParser.ENGINE = { NAME : NAME, VERSION : VERSION }; UAParser.OS = { NAME : NAME, VERSION : VERSION }; //UAParser.Utils = util; /////////// // Export ////////// // check js environment if (typeof(exports) !== UNDEF_TYPE) { // nodejs env if (typeof module !== UNDEF_TYPE && module.exports) { exports = module.exports = UAParser; } // TODO: test!!!!!!!! /* if (require && require.main === module && process) { // cli var jsonize = function (arr) { var res = []; for (var i in arr) { res.push(new UAParser(arr[i]).getResult()); } process.stdout.write(JSON.stringify(res, null, 2) + '\n'); }; if (process.stdin.isTTY) { // via args jsonize(process.argv.slice(2)); } else { // via pipe var str = ''; process.stdin.on('readable', function() { var read = process.stdin.read(); if (read !== null) { str += read; } }); process.stdin.on('end', function () { jsonize(str.replace(/\n$/, '').split('\n')); }); } } */ exports.UAParser = UAParser; } else { // requirejs env (optional) if ("function" === FUNC_TYPE && __webpack_require__(970)) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return UAParser; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (window) { // browser env window.UAParser = UAParser; } } // jQuery/Zepto specific (optional) // Note: // In AMD env the global scope should be kept clean, but jQuery is an exception. // jQuery always exports to global scope, unless jQuery.noConflict(true) is used, // and we should catch that. var $ = window && (window.jQuery || window.Zepto); if (typeof $ !== UNDEF_TYPE && !$.ua) { var parser = new UAParser(); $.ua = parser.getResult(); $.ua.get = function () { return parser.getUA(); }; $.ua.set = function (uastring) { parser.setUA(uastring); var result = parser.getResult(); for (var prop in result) { $.ua[prop] = result[prop]; } }; } })(typeof window === 'object' ? window : this); /***/ }), /* 970 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }), /* 971 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var invariant = __webpack_require__(10); var componentRegex = /\./; var orRegex = /\|\|/; var rangeRegex = /\s+\-\s+/; var modifierRegex = /^(<=|<|=|>=|~>|~|>|)?\s*(.+)/; var numericRegex = /^(\d*)(.*)/; /** * Splits input `range` on "||" and returns true if any subrange matches * `version`. * * @param {string} range * @param {string} version * @returns {boolean} */ function checkOrExpression(range, version) { var expressions = range.split(orRegex); if (expressions.length > 1) { return expressions.some(function (range) { return VersionRange.contains(range, version); }); } else { range = expressions[0].trim(); return checkRangeExpression(range, version); } } /** * Splits input `range` on " - " (the surrounding whitespace is required) and * returns true if version falls between the two operands. * * @param {string} range * @param {string} version * @returns {boolean} */ function checkRangeExpression(range, version) { var expressions = range.split(rangeRegex); !(expressions.length > 0 && expressions.length <= 2) ? true ? invariant(false, 'the "-" operator expects exactly 2 operands') : invariant(false) : void 0; if (expressions.length === 1) { return checkSimpleExpression(expressions[0], version); } else { var startVersion = expressions[0], endVersion = expressions[1]; !(isSimpleVersion(startVersion) && isSimpleVersion(endVersion)) ? true ? invariant(false, 'operands to the "-" operator must be simple (no modifiers)') : invariant(false) : void 0; return checkSimpleExpression('>=' + startVersion, version) && checkSimpleExpression('<=' + endVersion, version); } } /** * Checks if `range` matches `version`. `range` should be a "simple" range (ie. * not a compound range using the " - " or "||" operators). * * @param {string} range * @param {string} version * @returns {boolean} */ function checkSimpleExpression(range, version) { range = range.trim(); if (range === '') { return true; } var versionComponents = version.split(componentRegex); var _getModifierAndCompon = getModifierAndComponents(range), modifier = _getModifierAndCompon.modifier, rangeComponents = _getModifierAndCompon.rangeComponents; switch (modifier) { case '<': return checkLessThan(versionComponents, rangeComponents); case '<=': return checkLessThanOrEqual(versionComponents, rangeComponents); case '>=': return checkGreaterThanOrEqual(versionComponents, rangeComponents); case '>': return checkGreaterThan(versionComponents, rangeComponents); case '~': case '~>': return checkApproximateVersion(versionComponents, rangeComponents); default: return checkEqual(versionComponents, rangeComponents); } } /** * Checks whether `a` is less than `b`. * * @param {array} a * @param {array} b * @returns {boolean} */ function checkLessThan(a, b) { return compareComponents(a, b) === -1; } /** * Checks whether `a` is less than or equal to `b`. * * @param {array} a * @param {array} b * @returns {boolean} */ function checkLessThanOrEqual(a, b) { var result = compareComponents(a, b); return result === -1 || result === 0; } /** * Checks whether `a` is equal to `b`. * * @param {array} a * @param {array} b * @returns {boolean} */ function checkEqual(a, b) { return compareComponents(a, b) === 0; } /** * Checks whether `a` is greater than or equal to `b`. * * @param {array} a * @param {array} b * @returns {boolean} */ function checkGreaterThanOrEqual(a, b) { var result = compareComponents(a, b); return result === 1 || result === 0; } /** * Checks whether `a` is greater than `b`. * * @param {array} a * @param {array} b * @returns {boolean} */ function checkGreaterThan(a, b) { return compareComponents(a, b) === 1; } /** * Checks whether `a` is "reasonably close" to `b` (as described in * https://www.npmjs.org/doc/misc/semver.html). For example, if `b` is "1.3.1" * then "reasonably close" is defined as ">= 1.3.1 and < 1.4". * * @param {array} a * @param {array} b * @returns {boolean} */ function checkApproximateVersion(a, b) { var lowerBound = b.slice(); var upperBound = b.slice(); if (upperBound.length > 1) { upperBound.pop(); } var lastIndex = upperBound.length - 1; var numeric = parseInt(upperBound[lastIndex], 10); if (isNumber(numeric)) { upperBound[lastIndex] = numeric + 1 + ''; } return checkGreaterThanOrEqual(a, lowerBound) && checkLessThan(a, upperBound); } /** * Extracts the optional modifier (<, <=, =, >=, >, ~, ~>) and version * components from `range`. * * For example, given `range` ">= 1.2.3" returns an object with a `modifier` of * `">="` and `components` of `[1, 2, 3]`. * * @param {string} range * @returns {object} */ function getModifierAndComponents(range) { var rangeComponents = range.split(componentRegex); var matches = rangeComponents[0].match(modifierRegex); !matches ? true ? invariant(false, 'expected regex to match but it did not') : invariant(false) : void 0; return { modifier: matches[1], rangeComponents: [matches[2]].concat(rangeComponents.slice(1)) }; } /** * Determines if `number` is a number. * * @param {mixed} number * @returns {boolean} */ function isNumber(number) { return !isNaN(number) && isFinite(number); } /** * Tests whether `range` is a "simple" version number without any modifiers * (">", "~" etc). * * @param {string} range * @returns {boolean} */ function isSimpleVersion(range) { return !getModifierAndComponents(range).modifier; } /** * Zero-pads array `array` until it is at least `length` long. * * @param {array} array * @param {number} length */ function zeroPad(array, length) { for (var i = array.length; i < length; i++) { array[i] = '0'; } } /** * Normalizes `a` and `b` in preparation for comparison by doing the following: * * - zero-pads `a` and `b` * - marks any "x", "X" or "*" component in `b` as equivalent by zero-ing it out * in both `a` and `b` * - marks any final "*" component in `b` as a greedy wildcard by zero-ing it * and all of its successors in `a` * * @param {array} a * @param {array} b * @returns {array>} */ function normalizeVersions(a, b) { a = a.slice(); b = b.slice(); zeroPad(a, b.length); // mark "x" and "*" components as equal for (var i = 0; i < b.length; i++) { var matches = b[i].match(/^[x*]$/i); if (matches) { b[i] = a[i] = '0'; // final "*" greedily zeros all remaining components if (matches[0] === '*' && i === b.length - 1) { for (var j = i; j < a.length; j++) { a[j] = '0'; } } } } zeroPad(b, a.length); return [a, b]; } /** * Returns the numerical -- not the lexicographical -- ordering of `a` and `b`. * * For example, `10-alpha` is greater than `2-beta`. * * @param {string} a * @param {string} b * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, * or greater than `b`, respectively */ function compareNumeric(a, b) { var aPrefix = a.match(numericRegex)[1]; var bPrefix = b.match(numericRegex)[1]; var aNumeric = parseInt(aPrefix, 10); var bNumeric = parseInt(bPrefix, 10); if (isNumber(aNumeric) && isNumber(bNumeric) && aNumeric !== bNumeric) { return compare(aNumeric, bNumeric); } else { return compare(a, b); } } /** * Returns the ordering of `a` and `b`. * * @param {string|number} a * @param {string|number} b * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, * or greater than `b`, respectively */ function compare(a, b) { !(typeof a === typeof b) ? true ? invariant(false, '"a" and "b" must be of the same type') : invariant(false) : void 0; if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } /** * Compares arrays of version components. * * @param {array} a * @param {array} b * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to, * or greater than `b`, respectively */ function compareComponents(a, b) { var _normalizeVersions = normalizeVersions(a, b), aNormalized = _normalizeVersions[0], bNormalized = _normalizeVersions[1]; for (var i = 0; i < bNormalized.length; i++) { var result = compareNumeric(aNormalized[i], bNormalized[i]); if (result) { return result; } } return 0; } var VersionRange = { /** * Checks whether `version` satisfies the `range` specification. * * We support a subset of the expressions defined in * https://www.npmjs.org/doc/misc/semver.html: * * version Must match version exactly * =version Same as just version * >version Must be greater than version * >=version Must be greater than or equal to version * = 1.2.3 and < 1.3" * ~>version Equivalent to ~version * 1.2.x Must match "1.2.x", where "x" is a wildcard that matches * anything * 1.2.* Similar to "1.2.x", but "*" in the trailing position is a * "greedy" wildcard, so will match any number of additional * components: * "1.2.*" will match "1.2.1", "1.2.1.1", "1.2.1.1.1" etc * * Any version * "" (Empty string) Same as * * v1 - v2 Equivalent to ">= v1 and <= v2" * r1 || r2 Passes if either r1 or r2 are satisfied * * @param {string} range * @param {string} version * @returns {boolean} */ contains: function contains(range, version) { return checkOrExpression(range.trim(), version.trim()); } }; module.exports = VersionRange; /***/ }), /* 972 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; /***/ }), /* 973 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @typechecks static-only */ /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }), /* 974 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setDraftEditorSelection * @format * */ var DraftJsDebugLogging = __webpack_require__(975); var containsNode = __webpack_require__(195); var getActiveElement = __webpack_require__(448); var invariant = __webpack_require__(10); function getAnonymizedDOM(node, getNodeLabels) { if (!node) { return '[empty]'; } var anonymized = anonymizeTextWithin(node, getNodeLabels); if (anonymized.nodeType === Node.TEXT_NODE) { return anonymized.textContent; } !(anonymized instanceof Element) ? true ? invariant(false, 'Node must be an Element if it is not a text node.') : invariant(false) : void 0; return anonymized.outerHTML; } function anonymizeTextWithin(node, getNodeLabels) { var labels = getNodeLabels !== undefined ? getNodeLabels(node) : []; if (node.nodeType === Node.TEXT_NODE) { var length = node.textContent.length; return document.createTextNode('[text ' + length + (labels.length ? ' | ' + labels.join(', ') : '') + ']'); } var clone = node.cloneNode(); if (clone.nodeType === 1 && labels.length) { clone.setAttribute('data-labels', labels.join(', ')); } var childNodes = node.childNodes; for (var ii = 0; ii < childNodes.length; ii++) { clone.appendChild(anonymizeTextWithin(childNodes[ii], getNodeLabels)); } return clone; } function getAnonymizedEditorDOM(node, getNodeLabels) { // grabbing the DOM content of the Draft editor var currentNode = node; while (currentNode) { if (currentNode instanceof Element && currentNode.hasAttribute('contenteditable')) { // found the Draft editor container return getAnonymizedDOM(currentNode, getNodeLabels); } else { currentNode = currentNode.parentNode; } } return 'Could not find contentEditable parent of node'; } function getNodeLength(node) { return node.nodeValue === null ? node.childNodes.length : node.nodeValue.length; } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. */ function setDraftEditorSelection(selectionState, node, blockKey, nodeStart, nodeEnd) { // It's possible that the editor has been removed from the DOM but // our selection code doesn't know it yet. Forcing selection in // this case may lead to errors, so just bail now. if (!containsNode(document.documentElement, node)) { return; } var selection = global.getSelection(); var anchorKey = selectionState.getAnchorKey(); var anchorOffset = selectionState.getAnchorOffset(); var focusKey = selectionState.getFocusKey(); var focusOffset = selectionState.getFocusOffset(); var isBackward = selectionState.getIsBackward(); // IE doesn't support backward selection. Swap key/offset pairs. if (!selection.extend && isBackward) { var tempKey = anchorKey; var tempOffset = anchorOffset; anchorKey = focusKey; anchorOffset = focusOffset; focusKey = tempKey; focusOffset = tempOffset; isBackward = false; } var hasAnchor = anchorKey === blockKey && nodeStart <= anchorOffset && nodeEnd >= anchorOffset; var hasFocus = focusKey === blockKey && nodeStart <= focusOffset && nodeEnd >= focusOffset; // If the selection is entirely bound within this node, set the selection // and be done. if (hasAnchor && hasFocus) { selection.removeAllRanges(); addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState); addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState); return; } if (!isBackward) { // If the anchor is within this node, set the range start. if (hasAnchor) { selection.removeAllRanges(); addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState); } // If the focus is within this node, we can assume that we have // already set the appropriate start range on the selection, and // can simply extend the selection. if (hasFocus) { addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState); } } else { // If this node has the focus, set the selection range to be a // collapsed range beginning here. Later, when we encounter the anchor, // we'll use this information to extend the selection. if (hasFocus) { selection.removeAllRanges(); addPointToSelection(selection, node, focusOffset - nodeStart, selectionState); } // If this node has the anchor, we may assume that the correct // focus information is already stored on the selection object. // We keep track of it, reset the selection range, and extend it // back to the focus point. if (hasAnchor) { var storedFocusNode = selection.focusNode; var storedFocusOffset = selection.focusOffset; selection.removeAllRanges(); addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState); addFocusToSelection(selection, storedFocusNode, storedFocusOffset, selectionState); } } } /** * Extend selection towards focus point. */ function addFocusToSelection(selection, node, offset, selectionState) { var activeElement = getActiveElement(); if (selection.extend && containsNode(activeElement, node)) { // If `extend` is called while another element has focus, an error is // thrown. We therefore disable `extend` if the active element is somewhere // other than the node we are selecting. This should only occur in Firefox, // since it is the only browser to support multiple selections. // See https://bugzilla.mozilla.org/show_bug.cgi?id=921444. // logging to catch bug that is being reported in t16250795 if (offset > getNodeLength(node)) { // the call to 'selection.extend' is about to throw DraftJsDebugLogging.logSelectionStateFailure({ anonymizedDom: getAnonymizedEditorDOM(node), extraParams: JSON.stringify({ offset: offset }), selectionState: JSON.stringify(selectionState.toJS()) }); } // logging to catch bug that is being reported in t18110632 var nodeWasFocus = node === selection.focusNode; try { selection.extend(node, offset); } catch (e) { DraftJsDebugLogging.logSelectionStateFailure({ anonymizedDom: getAnonymizedEditorDOM(node, function (n) { var labels = []; if (n === activeElement) { labels.push('active element'); } if (n === selection.anchorNode) { labels.push('selection anchor node'); } if (n === selection.focusNode) { labels.push('selection focus node'); } return labels; }), extraParams: JSON.stringify({ activeElementName: activeElement ? activeElement.nodeName : null, nodeIsFocus: node === selection.focusNode, nodeWasFocus: nodeWasFocus, selectionRangeCount: selection.rangeCount, selectionAnchorNodeName: selection.anchorNode ? selection.anchorNode.nodeName : null, selectionAnchorOffset: selection.anchorOffset, selectionFocusNodeName: selection.focusNode ? selection.focusNode.nodeName : null, selectionFocusOffset: selection.focusOffset, message: e ? '' + e : null, offset: offset }, null, 2), selectionState: JSON.stringify(selectionState.toJS(), null, 2) }); // allow the error to be thrown - // better than continuing in a broken state throw e; } } else { // IE doesn't support extend. This will mean no backward selection. // Extract the existing selection range and add focus to it. // Additionally, clone the selection range. IE11 throws an // InvalidStateError when attempting to access selection properties // after the range is detached. var range = selection.getRangeAt(0); range.setEnd(node, offset); selection.addRange(range.cloneRange()); } } function addPointToSelection(selection, node, offset, selectionState) { var range = document.createRange(); // logging to catch bug that is being reported in t16250795 if (offset > getNodeLength(node)) { // in this case we know that the call to 'range.setStart' is about to throw DraftJsDebugLogging.logSelectionStateFailure({ anonymizedDom: getAnonymizedEditorDOM(node), extraParams: JSON.stringify({ offset: offset }), selectionState: JSON.stringify(selectionState.toJS()) }); } range.setStart(node, offset); selection.addRange(range); } module.exports = setDraftEditorSelection; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19))) /***/ }), /* 975 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftJsDebugLogging */ module.exports = { logSelectionStateFailure: function logSelectionStateFailure() { return null; } }; /***/ }), /* 976 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var isNode = __webpack_require__(977); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }), /* 977 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { var doc = object ? object.ownerDocument || object : document; var defaultView = doc.defaultView || window; return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }), /* 978 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var camelize = __webpack_require__(979); var hyphenate = __webpack_require__(980); function asString(value) /*?string*/{ return value == null ? value : String(value); } function getStyleProperty( /*DOMNode*/node, /*string*/name) /*?string*/{ var computedStyle = void 0; // W3C Standard if (window.getComputedStyle) { // In certain cases such as within an iframe in FF3, this returns null. computedStyle = window.getComputedStyle(node, null); if (computedStyle) { return asString(computedStyle.getPropertyValue(hyphenate(name))); } } // Safari if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = document.defaultView.getComputedStyle(node, null); // A Safari bug causes this to return null for `display: none` elements. if (computedStyle) { return asString(computedStyle.getPropertyValue(hyphenate(name))); } if (name === 'display') { return 'none'; } } // Internet Explorer if (node.currentStyle) { if (name === 'float') { return asString(node.currentStyle.cssFloat || node.currentStyle.styleFloat); } return asString(node.currentStyle[camelize(name)]); } return asString(node.style && node.style[camelize(name)]); } module.exports = getStyleProperty; /***/ }), /* 979 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }), /* 980 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }), /* 981 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var getElementRect = __webpack_require__(982); /** * Gets an element's position in pixels relative to the viewport. The returned * object represents the position of the element's top left corner. * * @param {DOMElement} element * @return {object} */ function getElementPosition(element) { var rect = getElementRect(element); return { x: rect.left, y: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; } module.exports = getElementPosition; /***/ }), /* 982 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var containsNode = __webpack_require__(195); /** * Gets an element's bounding rect in pixels relative to the viewport. * * @param {DOMElement} elem * @return {object} */ function getElementRect(elem) { var docElem = elem.ownerDocument.documentElement; // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect(). // IE9- will throw if the element is not in the document. if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) { return { left: 0, right: 0, top: 0, bottom: 0 }; } // Subtracts clientTop/Left because IE8- added a 2px border to the // element (see http://fburl.com/1493213). IE 7 in // Quicksmode does not report clientLeft/clientTop so there // will be an unaccounted offset of 2px when in quirksmode var rect = elem.getBoundingClientRect(); return { left: Math.round(rect.left) - docElem.clientLeft, right: Math.round(rect.right) - docElem.clientLeft, top: Math.round(rect.top) - docElem.clientTop, bottom: Math.round(rect.bottom) - docElem.clientTop }; } module.exports = getElementRect; /***/ }), /* 983 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var isWebkit = typeof navigator !== 'undefined' && navigator.userAgent.indexOf('AppleWebKit') > -1; /** * Gets the element with the document scroll properties such as `scrollLeft` and * `scrollHeight`. This may differ across different browsers. * * NOTE: The return value can be null if the DOM is not yet ready. * * @param {?DOMDocument} doc Defaults to current document. * @return {?DOMElement} */ function getDocumentScrollElement(doc) { doc = doc || document; if (doc.scrollingElement) { return doc.scrollingElement; } return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body; } module.exports = getDocumentScrollElement; /***/ }), /* 984 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable.Window && scrollable instanceof scrollable.Window) { return { x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft, y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }), /* 985 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function getViewportWidth() { var width = void 0; if (document.documentElement) { width = document.documentElement.clientWidth; } if (!width && document.body) { width = document.body.clientWidth; } return width || 0; } /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @typechecks */ function getViewportHeight() { var height = void 0; if (document.documentElement) { height = document.documentElement.clientHeight; } if (!height && document.body) { height = document.body.clientHeight; } return height || 0; } /** * Gets the viewport dimensions including any scrollbars. */ function getViewportDimensions() { return { width: window.innerWidth || getViewportWidth(), height: window.innerHeight || getViewportHeight() }; } /** * Gets the viewport dimensions excluding any scrollbars. */ getViewportDimensions.withoutScrollbars = function () { return { width: getViewportWidth(), height: getViewportHeight() }; }; module.exports = getViewportDimensions; /***/ }), /* 986 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks static-only */ /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} className * @return {string} */ function joinClasses(className /*, ... */) { if (!className) { className = ''; } var nextClass = void 0; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }), /* 987 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorDragHandler * @format * */ var DataTransfer = __webpack_require__(450); var DraftModifier = __webpack_require__(23); var EditorState = __webpack_require__(15); var findAncestorOffsetKey = __webpack_require__(198); var getTextContentFromFiles = __webpack_require__(452); var getUpdatedSelectionState = __webpack_require__(453); var isEventHandled = __webpack_require__(104); var nullthrows = __webpack_require__(35); /** * Get a SelectionState for the supplied mouse event. */ function getSelectionForEvent(event, editorState) { var node = null; var offset = null; if (typeof document.caretRangeFromPoint === 'function') { var dropRange = document.caretRangeFromPoint(event.x, event.y); node = dropRange.startContainer; offset = dropRange.startOffset; } else if (event.rangeParent) { node = event.rangeParent; offset = event.rangeOffset; } else { return null; } node = nullthrows(node); offset = nullthrows(offset); var offsetKey = nullthrows(findAncestorOffsetKey(node)); return getUpdatedSelectionState(editorState, offsetKey, offset, offsetKey, offset); } var DraftEditorDragHandler = { /** * Drag originating from input terminated. */ onDragEnd: function onDragEnd(editor) { editor.exitCurrentMode(); }, /** * Handle data being dropped. */ onDrop: function onDrop(editor, e) { var data = new DataTransfer(e.nativeEvent.dataTransfer); var editorState = editor._latestEditorState; var dropSelection = getSelectionForEvent(e.nativeEvent, editorState); e.preventDefault(); editor.exitCurrentMode(); if (dropSelection == null) { return; } var files = data.getFiles(); if (files.length > 0) { if (editor.props.handleDroppedFiles && isEventHandled(editor.props.handleDroppedFiles(dropSelection, files))) { return; } getTextContentFromFiles(files, function (fileText) { fileText && editor.update(insertTextAtSelection(editorState, dropSelection, fileText)); }); return; } var dragType = editor._internalDrag ? 'internal' : 'external'; if (editor.props.handleDrop && isEventHandled(editor.props.handleDrop(dropSelection, data, dragType))) { return; } if (editor._internalDrag) { editor.update(moveText(editorState, dropSelection)); return; } editor.update(insertTextAtSelection(editorState, dropSelection, data.getText())); } }; function moveText(editorState, targetSelection) { var newContentState = DraftModifier.moveText(editorState.getCurrentContent(), editorState.getSelection(), targetSelection); return EditorState.push(editorState, newContentState, 'insert-fragment'); } /** * Insert text at a specified selection. */ function insertTextAtSelection(editorState, selection, text) { var newContentState = DraftModifier.insertText(editorState.getCurrentContent(), selection, text, editorState.getCurrentInlineStyle()); return EditorState.push(editorState, newContentState, 'insert-fragment'); } module.exports = DraftEditorDragHandler; /***/ }), /* 988 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ var PhotosMimeType = { isImage: function isImage(mimeString) { return getParts(mimeString)[0] === 'image'; }, isJpeg: function isJpeg(mimeString) { var parts = getParts(mimeString); return PhotosMimeType.isImage(mimeString) && ( // see http://fburl.com/10972194 parts[1] === 'jpeg' || parts[1] === 'pjpeg'); } }; function getParts(mimeString) { return mimeString.split('/'); } module.exports = PhotosMimeType; /***/ }), /* 989 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @typechecks */ var invariant = __webpack_require__(10); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? true ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? true ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? true ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? true ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /***/ }), /* 990 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DraftEditorEditHandler * @format * */ var onBeforeInput = __webpack_require__(991); var onBlur = __webpack_require__(994); var onCompositionStart = __webpack_require__(995); var onCopy = __webpack_require__(996); var onCut = __webpack_require__(997); var onDragOver = __webpack_require__(998); var onDragStart = __webpack_require__(999); var onFocus = __webpack_require__(1000); var onInput = __webpack_require__(1001); var onKeyDown = __webpack_require__(1002); var onPaste = __webpack_require__(1016); var onSelect = __webpack_require__(1021); var DraftEditorEditHandler = { onBeforeInput: onBeforeInput, onBlur: onBlur, onCompositionStart: onCompositionStart, onCopy: onCopy, onCut: onCut, onDragOver: onDragOver, onDragStart: onDragStart, onFocus: onFocus, onInput: onInput, onKeyDown: onKeyDown, onPaste: onPaste, onSelect: onSelect }; module.exports = DraftEditorEditHandler; /***/ }), /* 991 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule editOnBeforeInput * @format * */ var BlockTree = __webpack_require__(442); var DraftModifier = __webpack_require__(23); var EditorState = __webpack_require__(15); var UserAgent = __webpack_require__(44); var getEntityKeyForSelection = __webpack_require__(194); var isEventHandled = __webpack_require__(104); var isSelectionAtLeafStart = __webpack_require__(446); var nullthrows = __webpack_require__(35); var setImmediate = __webpack_require__(992); // When nothing is focused, Firefox regards two characters, `'` and `/`, as // commands that should open and focus the "quickfind" search bar. This should // *never* happen while a contenteditable is focused, but as of v28, it // sometimes does, even when the keypress event target is the contenteditable. // This breaks the input. Special case these characters to ensure that when // they are typed, we prevent default on the event to make sure not to // trigger quickfind. var FF_QUICKFIND_CHAR = "'"; var FF_QUICKFIND_LINK_CHAR = '/'; var isFirefox = UserAgent.isBrowser('Firefox'); function mustPreventDefaultForCharacter(character) { return isFirefox && (character == FF_QUICKFIND_CHAR || character == FF_QUICKFIND_LINK_CHAR); } /** * Replace the current selection with the specified text string, with the * inline style and entity key applied to the newly inserted text. */ function replaceText(editorState, text, inlineStyle, entityKey) { var contentState = DraftModifier.replaceText(editorState.getCurrentContent(), editorState.getSelection(), text, inlineStyle, entityKey); return EditorState.push(editorState, contentState, 'insert-characters'); } /** * When `onBeforeInput` executes, the browser is attempting to insert a * character into the editor. Apply this character data to the document, * allowing native insertion if possible. * * Native insertion is encouraged in order to limit re-rendering and to * preserve spellcheck highlighting, which disappears or flashes if re-render * occurs on the relevant text nodes. */ function editOnBeforeInput(editor, e) { if (editor._pendingStateFromBeforeInput !== undefined) { editor.update(editor._pendingStateFromBeforeInput); editor._pendingStateFromBeforeInput = undefined; } var editorState = editor._latestEditorState; var chars = e.data; // In some cases (ex: IE ideographic space insertion) no character data // is provided. There's nothing to do when this happens. if (!chars) { return; } // Allow the top-level component to handle the insertion manually. This is // useful when triggering interesting behaviors for a character insertion, // Simple examples: replacing a raw text ':)' with a smile emoji or image // decorator, or setting a block to be a list item after typing '- ' at the // start of the block. if (editor.props.handleBeforeInput && isEventHandled(editor.props.handleBeforeInput(chars, editorState))) { e.preventDefault(); return; } // If selection is collapsed, conditionally allow native behavior. This // reduces re-renders and preserves spellcheck highlighting. If the selection // is not collapsed, we will re-render. var selection = editorState.getSelection(); var selectionStart = selection.getStartOffset(); var selectionEnd = selection.getEndOffset(); var anchorKey = selection.getAnchorKey(); if (!selection.isCollapsed()) { e.preventDefault(); // If the currently selected text matches what the user is trying to // replace it with, let's just update the `SelectionState`. If not, update // the `ContentState` with the new text. var currentlySelectedChars = editorState.getCurrentContent().getPlainText().slice(selectionStart, selectionEnd); if (chars === currentlySelectedChars) { editor.update(EditorState.forceSelection(editorState, selection.merge({ focusOffset: selectionEnd }))); } else { editor.update(replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()))); } return; } var newEditorState = replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection())); // Bunch of different cases follow where we need to prevent native insertion. var mustPreventNative = false; if (!mustPreventNative) { // Browsers tend to insert text in weird places in the DOM when typing at // the start of a leaf, so we'll handle it ourselves. mustPreventNative = isSelectionAtLeafStart(editor._latestCommittedEditorState); } if (!mustPreventNative) { // Chrome will also split up a node into two pieces if it contains a Tab // char, for no explicable reason. Seemingly caused by this commit: // https://chromium.googlesource.com/chromium/src/+/013ac5eaf3%5E%21/ var nativeSelection = global.getSelection(); // Selection is necessarily collapsed at this point due to earlier check. if (nativeSelection.anchorNode && nativeSelection.anchorNode.nodeType === Node.TEXT_NODE) { // See isTabHTMLSpanElement in chromium EditingUtilities.cpp. var parentNode = nativeSelection.anchorNode.parentNode; mustPreventNative = parentNode.nodeName === 'SPAN' && parentNode.firstChild.nodeType === Node.TEXT_NODE && parentNode.firstChild.nodeValue.indexOf('\t') !== -1; } } if (!mustPreventNative) { // Check the old and new "fingerprints" of the current block to determine // whether this insertion requires any addition or removal of text nodes, // in which case we would prevent the native character insertion. var originalFingerprint = BlockTree.getFingerprint(editorState.getBlockTree(anchorKey)); var newFingerprint = BlockTree.getFingerprint(newEditorState.getBlockTree(anchorKey)); mustPreventNative = originalFingerprint !== newFingerprint; } if (!mustPreventNative) { mustPreventNative = mustPreventDefaultForCharacter(chars); } if (!mustPreventNative) { mustPreventNative = nullthrows(newEditorState.getDirectionMap()).get(anchorKey) !== nullthrows(editorState.getDirectionMap()).get(anchorKey); } if (mustPreventNative) { e.preventDefault(); editor.update(newEditorState); return; } // We made it all the way! Let the browser do its thing and insert the char. newEditorState = EditorState.set(newEditorState, { nativelyRenderedContent: newEditorState.getCurrentContent() }); // The native event is allowed to occur. To allow user onChange handlers to // change the inserted text, we wait until the text is actually inserted // before we actually update our state. That way when we rerender, the text // we see in the DOM will already have been inserted properly. editor._pendingStateFromBeforeInput = newEditorState; setImmediate(function () { if (editor._pendingStateFromBeforeInput !== undefined) { editor.update(editor._pendingStateFromBeforeInput); editor._pendingStateFromBeforeInput = undefined; } }); } module.exports = editOnBeforeInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19))) /***/ }), /* 992 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ // setimmediate adds setImmediate to the global. We want to make sure we export // the actual function. __webpack_require__(993); module.exports = global.setImmediate; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19))) /***/ }), /* 993 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a